首页 > 解决方案 > PHP For循环迭代应该调整

问题描述

我有一个 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但它不起作用。我不知道如何解决这个问题。

任何建议将不胜感激

标签: phphtml

解决方案


有很多方法可以更轻松地做到这一点,这里有一个:

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

匹配 1 个或多个数字\d+。你的数组将在$matches[0].


推荐阅读