【问题标题】:php: find any combination of 2 or 3 numbers in string and separate as variablephp:在字符串中查找 2 或 3 个数字的任意组合并作为变量分隔
【发布时间】:2016-03-02 11:00:57
【问题描述】:

如何查找字符串中是否存在 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";

【问题讨论】:

  • 数字总是在字符串的末尾吗?只有一个数字?
  • yes 总是在最后,可以是 2 位或 3 位数字

标签: php string variables split explode


【解决方案1】:

没试过,但应该可以。

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

【讨论】:

  • 如何将代码中的数字限制为 2 位或 3 位?
  • 它会给你整数。告诉我如果数字是 1000 会发生什么。如果它大于 999,您可以禁止它或小于 10。
  • 你不应该先检查字符串中是否有数字吗?与 preg_match?说字符串不包含任何数字...
  • 那么 $number 将是 null 并且当您尝试替换它时,php 不会替换它。所以最后你的$number 将是null,这是正确的,因为没有数字,$text 将是相同的字符串,没有任何变化,这也是正确的。使用这种方式,你会跳过 if 条件。如果在字符串中找不到数字,不要担心 php 不会引发错误。
【解决方案2】:

另一个

$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
- - - - 

Example Code

【讨论】:

  • 对不起,我忘了说我只有一个字符串,它是用户输入的。
【解决方案3】:

试试这个

<?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
)

【讨论】:

  • 对不起,我忘了说我只有一个字符串,它是用户输入的。
  • 所以你只需使用 $combine = explode(' ',$string1);并删除字符串2,其余代码相同
【解决方案4】:

你试试这个代码

$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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    相关资源
    最近更新 更多