Php 0的strpos在循环期间中断

Php 0的strpos在循环期间中断,php,while-loop,offset,strpos,Php,While Loop,Offset,Strpos,所以我再次练习PHP。特别是while循环中的strpos() 下面代码的问题是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, $fi

所以我再次练习PHP。特别是while循环中的
strpos()

下面代码的问题是
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;
}
$string='orem ipsum door sit amet,concetetur adipising elit';
$find='o';
$offset=0;
$length=strlen($find);
而($string_pos=strpos($string,$find,$offset)){
回显“字符串”。$find。在位置“$String_pos”找到。
”; $offset=$length+$string\u pos; }

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

如果您不想使用
strpos()


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

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

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

代码:()

输出:

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\u match\u all()
all是一种过分的手段。然而,如果你想数数多个不同的单词,或者整个单词,或者其他一些棘手的事情,它可能是正确的工具


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

如果你说这样的话,你可能会修复你的循环:
while($string\u pos=strpos($string,$find,$offset))!==false)
如果你查看文档,它会说明并显示使用===或!==以避免将0的值强制转换为false。该!==虚假的作品,但我不太明白为什么。我的脑子都转不过来了,“不等于假”怎么纠正这个问题呢?它是否作为必要的if语句?类似于“如果0返回0不为false”。我知道我很笨,但它似乎没有为我“点击”一下。
==之所以有效,是因为
0
while
视为
false
。所以通过
==我们强制
strpos
精确检查
false
。希望这是明确的。在我看来,这是一个糟糕的建议。性能方面,可用性方面,功能方面。
$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,
)