[英]Php endless loop over and over?
<?php
$offset = 0;
$find = "is";
$find_length = strlen($find);
$string = "This is a string, and it is an example.";
while($string_position = strpos($string, $find, $offset)){
echo $find. " Found at ". $string_position ."<br>";
$offset = string_position + find_length;
}
?>
keeping getting "is Found at 2" over and over.一遍又一遍地保持“在 2 时发现”。 i am expecting " is found at 2", then 5, then 25我期待“在 2 处找到”,然后是 5,然后是 25
$offset = string_position + find_length;
Use variables instead of constants使用变量而不是常量
$offset = $string_position + $find_length;
If the needle is found at the beginning of the string, strpos()
returns 0
, which means, that the loop will never start.如果在字符串的开头找到针,则strpos()
返回0
,这意味着循环永远不会开始。
while(($string_position = strpos($string, $find, $offset)) !== false) {
// code
}
Additional change your error settings in your development environment额外更改开发环境中的错误设置
error_reporting(E_ALL | E_STRICT);
Now you will get this as notice现在你会得到这个通知
PHP Notice: Use of undefined constant string_position - assumed 'string_position' in php > shell code on line 4
PHP Stack trace:
PHP 1. {main}() php shell code:0
Notice: Use of undefined constant string_position - assumed 'string_position' in php shell > code on line 4
Call Stack:
1.2172 636208 1. {main}() php shell code:0
PHP Notice: Use of undefined constant find_length - assumed 'find_length' in php shell code on line 4
PHP Stack trace:
PHP 1. {main}() php shell code:0
Notice: Use of undefined constant find_length - assumed 'find_length' in php shell code on line 4
Call Stack:
1.2172 636208 1. {main}() php shell code:0
$
sign is missing at: $
符号在以下位置丢失:
$offset = string_position + find_length;
Also, a small bug: if the string is found at position 0, the loop will end.此外,还有一个小错误:如果在 position 0 处找到字符串,则循环将结束。
missing some $, try:缺少一些 $,请尝试:
$offset = $string_position + $find_length;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.