这是因为你在htmlspecialchars($str)上使用了strpos,但你在$str上使用了substr.
htmlspecialchars()将特殊字符转换为HTML实体.举一个小例子:
// search 'foo' in '&foobar'
$str = "&foobar";
$toFind = "foo";
// htmlspecialchars($str) gives you "&foobar"
// as & is replaced by &. strpos returns 5
$pos = strpos(htmlspecialchars($str),$toFind);
// now your try and extract 3 char starting at index 5!!! in the original
// string even though its 'foo' starts at index 1.
echo substr($str,strlen($toFind)); // prints ar
要解决这个问题,请在两个函数中使用相同的haystack.
要回答你在其他问题中找到一个字符串的所有出现的其他问题,你可以使用strpos的第三个参数offset,它指定从哪里搜索.例:
$str = "&foobar&foobaz";
$toFind = "foo";
$start = 0;
while($pos = strpos(($str),$toFind,$start) !== false) {
echo 'Found '.$toFind.' at position '.$pos."\n";
$start = $pos+1; // start searching from next position.
}
Found foo at position 1 Found foo at position 8