PHP For循环迭代应调整

时间:2019-10-24 21:14:03

标签: php html

我有一个for循环,旨在从提供给它的各种字符串中提取所有数字。我将提取的数字保存在数组中。我的代码如下:

$length = strlen($RouteString); 
$data = [];
$index = 0;     
for($i = 0; $i < $length; $i++)
{           
    $j = 1;
    $count = 0;
    while(is_numeric(substr($RouteString,$i,$j)) == true)
    {
        $data[$index] = substr($RouteString,$i,$j);
        $j = $j+1;          
    }

    if(is_numeric(substr($RouteString,$i,1)) == true)
    {
        $index = $index + 1;
    }
}

$Routestring设置为:"B12-1234-U102-D4-11-19-E",应给出$data=[12,1234,102,4,11,19]的结果,但应给出$data=[12,2,1234,234,34,4,102,02,2,4,11,1,19,9]

我已尝试通过调整$index来解决问题,但是它不起作用。我不知道如何解决这个问题。

任何建议将不胜感激

3 个答案:

答案 0 :(得分:3)

有许多方法可以简化此操作,这是一种:

preg_match_all('/\d+/', $string, $matches);

匹配1个或多个数字\d+。您的数组将位于$matches[0]中。

答案 1 :(得分:0)

如果不涉及其他变量,这应该可以工作:

已更新

$str = "B12-1234-U102-D4-11-19-E";
$result = preg_split("/\D/", $str, -1, PREG_SPLIT_NO_EMPTY);

答案 2 :(得分:0)

这就是我要做的:

$str = 'B12-1234-U102-D4-11-19-E';
$data = array_map('intval', array_filter(preg_split("/\D+/", $str)));
  • preg_split将返回仅包含数字的数组。

  • array_filter将从结果中删除所有空值。

  • array_map会将所有结果转换为整数。

如果密钥有问题,可以使用array_values重置它们。

Sandbox