PHP For循环迭代应该进行调整

PHP For循环迭代应该进行调整,php,html,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)) == tr

我有一个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;
    }
}
$length=strlen($RouteString);
$data=[];
$index=0;
对于($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(是数值的(substr($RouteString,$i,1))==true)
{
$index=$index+1;
}
}
$Routestring
设置为:
“B12-1234-U102-D4-11-19-E”
并应给出
$data=[121234102,4,11,19]
的结果,但它给出的是
$data=[12,21234234,4102,02,2,4,11,1,19,9]

我已尝试通过调整
$index
来解决此问题,但不起作用。我想不出怎么解决这个问题


任何建议都将不胜感激

如果不涉及其他变量,这将起作用:

更新


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

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

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

我将这样做:

$str='B12-1234-U102-D4-11-19-E';
$data=array_-map('intval',array_-filter(preg_-split(“/\D+/”,$str));
  • preg_split
    将返回仅包含数字的数组

  • array\u filter
    将从结果中删除所有空值

  • array\u map
    将所有结果转换为整数

如果按键有问题,可以使用
array\u值
重置按键


如果你只是用一根管子替换所有非数字,然后用管子分解,这行得通吗?我认为这可能是解决这个问题的更好、更快的方法,但显然不能像现在这样回答您的问题。@zbee我尝试了您的方法,但它创建了空数组项,这与我在代码中使用$index而不是$I的原因相同。请参阅Abracadver的答案了解我的意思。它返回的正是您所说的目标,但要简洁得多。请解释您使用的
preg\u split()
。我尝试了您建议的此方法,但它会创建空数组项,这与我在代码中使用$index而不是$I的原因相同。有一个
PREG\u SPLIT\u NO\u EMPTY
标志,但是
PREG\u SPLIT
可能不是这个工作的最佳工具。@Stephan您能显示生成空数组项的代码吗?这段代码和另一个答案中的代码都提供了您所说的要达到的结果集。非常感谢
preg_match_all('/\d+/', $string, $matches);