0的strpos在循环时中断


strpos of 0 breaking while loop

所以我又在练习PHP了。特别是while循环中的CCD_ 1。

以下代码的问题在于,strpos()在第一个循环中导致0,而在while条件中则产生false结果,从而终止循环。

$string = 'orem ipsum dolor sit amet, consectetur adipisicing elit.';
$find = 'o';
$offset = 0;
$length  = strlen($find);
while ($string_pos = strpos($string, $find, $offset)) {
    echo 'String '.$find.' found at position '.$string_pos.'.<br>';
    $offset = $length + $string_pos;
}

我对这一切都很陌生,有人能帮我解释一下并找到解决方案吗?我正在寻找它来循环所有的事件。

如果您不想使用strpos():

<?php
$string = 'orem ipsum dolor sit amet, consectetur adipisicing elit.';
$find = 'o';
for($i = 0; $i <= strlen($string)-1; $i++){
    // we are checking with each index of the string here
    if($string[$i] == $find){
        echo 'String '.$find.' found at position '.$i.'.<br>';
    }
}
?>

我不太喜欢Jigar的"迭代每个字符"答案,因为当找不到更多指针时,它不会提供快速退出(不管怎样,它都会迭代整个字符串)——这在较长的字符串中可能会变得更贵。假设你有一个10000个字符的字符串,指针只出现在第一个字符上——这意味着要对没有可用输出的情况进行9999次迭代检查。事实上,我没有做任何基准测试,这可能根本不是什么大事。

至于您的方法,您只需要对strpos()的结果进行严格的比较,以便php能够正确区分false0的结果。要实现这一点,您只需要将strpos()声明封装在括号中,并编写一个特定于类型的比较(strpos()0)。

以下是另外两种方式(非正则表达式和正则表达式):

代码:(演示)

$string='orem ipsum dolor sit amet, consectetur adipisicing elit.';
$find='o';
$offset=0;
$length=strlen($find);
while(($string_pos=strpos($string,$find,$offset))!==false){  // just use a strict comparison
    echo "String $find found at position $string_pos'n";
    $offset=$length+$string_pos;
}
echo "'n";
var_export(preg_match_all('/o/',$string,$out,PREG_OFFSET_CAPTURE)?array_column($out[0],1):'no matches');

输出:

String o found at position 0
String o found at position 12
String o found at position 14
String o found at position 28
array (
  0 => 0,
  1 => 12,
  2 => 14,
  3 => 28,
)

就你的情况而言,preg_match_all()太夸张了。然而,如果你想计算多个不同的单词,或整个单词,或其他棘手的东西,它可能是正确的工具。

除此之外,根据搜索场景的不同,str_word_count()有一个设置,它可以返回字符串中所有单词的偏移量,然后您可以调用一个过滤函数来只保留您想要的单词。我只是想把这个建议留给未来的读者;它不适用于这个问题。