Find multiple string positions in PHP
This happens because you are using strpos
on the htmlspecialchars($str)
but you are using substr
on $str
.
htmlspecialchars()
converts special characters to HTML entities. 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 haystack in both the functions.
To answer you other question of finding all the occurrences of one string in other, you can make use of the 3rd argument of strpos
, offset, which specifies where to search from. 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; // start searching from next position.
}
Output:
Found foo at position 1
Found foo at position 8
Use:
while( ($pos = strpos(($str),$toFind,$start)) != false) {
Explenation:
Set )
after false behind $start)
, so that $pos = strpos(($str),$toFind,$start)
is placed between ()
.
Also use != false
, because php.net says:
'This function may return Boolean FALSE
, but may also return a non-Boolean value which evaluates to FALSE
, such as 0
or ""
. Please read the section on Booleans for more information. Use the ===
operator for testing the return value of this function.
$string = '\n;alskdjf;lkdsajf;lkjdsaf \n hey judeee \n';
$pattern = '\n';
$start = 0;
while(($newLine = strpos($string, $pattern, $start)) !== false){
$start = $newLine + 1;
echo $newLine . '<br>';
}
This works out of the gate, and doesn't run an infinite loop like the above, and the !== allows for a match at position 0.