(php)while循环中的strpos偏移量

时间:2014-06-01 04:23:50

标签: php while-loop strpos

我在这个网站上学习php阅读教程(http://www.tizag.com/) 以下是教程的摘录。

<?php
$numberedString="1234567890123456789012345678901234567890";
$offset=0;
$fiveCounter=0;
echo $numberedString;
if(strpos($numberedString, "5")==0){
    $fiveCounter++;
    echo "<br />Five #$fiveCounter is at position - 0";
}
while($offset=strpos($numberedString, "5", $offset+1)){
    $fiveCounter++;
    echo "<br />Five #$fiveCounter is at position - $offset";
}?>

我不明白偏移是如何变化的。 while()中的代码不应该是真的吗?这似乎是指定偏移量。 我理解第一个偏移是0.当它进入

while($offset=strpos($numberedString, "5", $offset+1)

第一次,由于'$ offset + 1',偏移量变为1。 然后,我想

strops($numberedString, "5", $offset+1)

变为4。

我猜4再次偏移,再次开始循环,但是 为什么while()中的代码可以指定别的东西? 输出什么不应该是真的吗?

2 个答案:

答案 0 :(得分:2)

Hanky的答案是正确的,但我会填写一些细节,因为你正在研究你正在尝试学习PHP的教程。

在脚本的开头,变量$offset设置为0.第一次while循环运行(如果在if语句继续中的位置1中未识别出5),则偏移量将增加1(while循环中$offset+1函数中的strpos)这样做也会增加上面的$ offset变量。 strpos函数将返回字符串中下一个5的位置(从而再次更改$offset变量的值,这次是最新的位置5)或返回false并在效果结束循环执行。

答案 1 :(得分:1)

根据strops手册

  

<强>偏移

     

如果指定,搜索将从字符串的开头开始计算此字符数。

偏移量不断变化,因为strops仅返回第一次出现针5的位置,然后告诉它在该位置之后开始搜索以进行下一次迭代,依此类推。偏移量将继续变化,直到strops返回字符串中不再有5可用

$offset+1仅在循环中用于告知strops开始搜索之前获得的after位置。它不会增加$offset变量的值。

请稍微澄清一下,(只更改了一个变量的名称)

<?php
$numberedString="1234567890123456789012345678901234567890";
$lastPosition=0;
while($currentPosition=strpos($numberedString, "5", $lastPosition+1)){
    echo "Present at $currentPosition <br>";
    $lastPosition=$currentPosition;
}
?>

修改 事实上,你应该试着这个让它更容易理解

$numberedString="1234567890123456789012345678901234567890";
echo "Haystack is ".$numberedString;
$lastPosition=0;
while($currentPosition=strpos($numberedString, "5", $lastPosition+1)){
    echo "\nPresent at $currentPosition and now the haystack will be ".substr($numberedString,$currentPosition);
    $lastPosition=$currentPosition;
}

<强>输出

Haystack is 1234567890123456789012345678901234567890
Present at 4 and now the haystack will be 567890123456789012345678901234567890
Present at 14 and now the haystack will be 56789012345678901234567890
Present at 24 and now the haystack will be 5678901234567890
Present at 34 and now the haystack will be 567890