Php endless loop over and over?
<?php
开发者_如何学Go$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 . i am expecting " is found at 2", then 5, then 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.
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.
missing some $, try :
$offset = $string_position + $find_length;
精彩评论