<?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;
}
?>
一遍又一遍地“获得2”。我期待“发现在2”,然后是5,然后是25
答案 0 :(得分:1)
$offset = string_position + find_length;
使用变量而不是常量
$offset = $string_position + $find_length;
如果在字符串的开头找到了针,strpos()
会返回0
,这意味着循环永远不会启动。
while(($string_position = strpos($string, $find, $offset)) !== false) {
// code
}
在开发环境中进行其他更改错误设置
error_reporting(E_ALL | E_STRICT);
现在你会得到这个通知
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
答案 1 :(得分:1)
$
符号遗失在:
$offset = string_position + find_length;
另外,一个小错误:如果在位置0找到字符串,循环将结束。
答案 2 :(得分:1)
缺少一些$,请尝试:
$offset = $string_position + $find_length;