PHP在数组中查找两个连续的数字条目

时间:2017-10-06 00:09:20

标签: php

我的问题是它只是复制了两次数字,虽然它确实在有数字时添加了中断,但我试图检查数字后面是否有数字,所以它会说第12行是.....

感谢您的帮助

<?PHP
$lines =  file_get_contents('http://www.webstitcher.com/test.txt');
$tag = str_split($lines); // puts all lines into a array
foreach ($tag as $num => $letta){
    if (is_numeric($letta) == TRUE){
        $num2 = $num++;
        if (is_numeric($tag[$num2])){ // checks if next line is going to be another digit
        $letta .= $tag[$num2];
        unset($tag[$num2]); // removes line if it had another digit and adds to ouput
        }
            echo '<br />' . $letta;
        } 
        else {
    echo $letta;
        }
}

?>

1 个答案:

答案 0 :(得分:0)

尝试使用' '作为分隔符来爆炸字符串。这将使您能够保持整数,并最终有助于减少很多复杂性。

$lines =  file_get_contents('http://www.webstitcher.com/test.txt');
$tag = explode(' ', $lines); // puts all words into a array
foreach ($tag as $word){
    if (is_numeric($word)) {
        // if the word is numeric, simply skip to next line
        // if you need to keep the number, add $word to the echo statement
        echo '<br />';
    } 
    else {
        echo ' '.$word;
    }
}

这样您就不必跟踪数组中的前一个元素或检查下一个元素。

或者,您也可以使用preg_replace来完全消除循环的需要。

$lines = preg_replace('/[0-9]+/', '<br>', $words);