PHP:在字符串中查找 2 或 3 个数字的任意组合,并作为变量分开


php: find any combination of 2 or 3 numbers in string and separate as variable

如何查找字符串中是否存在 2 或 3 个数字的组合,然后将其拆分为两个变量?

示例:$input = "this and that 12"$input = "this and that 100"

我想将此字符串分为两个变量:

$text = "this and that",

$number = "12"(或如上例中的"100")

P.S字符串是用户输入,也可以不包含任何数字,示例$input = "this and that";

没有尝试过,但应该可以工作。

$number = preg_replace( '/[^0-9]/', '', $string );
$text = str_replace($number, "", $string);

另一个

$aStrings = array('This and that 123','This and Not That 12');
foreach($aStrings as $str){
preg_match('/'D+/',$str, $text);
preg_match('/'d+/', $str, $num);
echo "
$text[0]
$num[0]
- - - - 
";
}

输出:

This and that 
123
- - - - 
This and Not That 
12
- - - - 

示例代码

试试这个

<?php 
$string1 = "this and that 12"; 
$string2 = "this and that 100";
$combine = explode(' ',$string1.' '.$string2);
$vars  = '';
$integer ='';
foreach($combine as $key =>$val)
{
    if(is_numeric($val))
    {
        $vars[] = $val;
    }
    else
    {
        $integer[] =$val;
    }
}
echo "<pre>"; print_r(array_unique($vars));
echo "<pre>"; print_r(array_unique($integer));
?>

这将输出

Array
(
    [0] => 12
    [1] => 100
)
Array
(
    [0] => this
    [1] => and
    [2] => that
)

你试试这段代码

$string="this and that 12";//this and that 100
preg_match_all('/^([^'d]+)('d+)/', $string, $match);
echo $text = $match[1][0];
echo $num = $match[2][0];