This is because you use strpos in htmlspecialchars($str) , but you use substr on $str .
htmlspecialchars() converts special characters to HTML objects. Take a small example:
// 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,$pos,strlen($toFind)); // prints ar
To fix this, use the same hay in both functions.
To answer another question about finding all occurrences of one line in another, you can use the third argument, strpos , offset, which determines where to look. Example:
$str = "&foobar&foobaz"; $toFind = "foo"; $start = 0; while($pos = strpos(($str),$toFind,$start) !== false) { echo 'Found '.$toFind.' at position '.$pos."\n"; $start = $pos+1;
Output:
Found foo in position 1
Found foo at position 8
codaddict
source share