How to find all occurrence position of a substring in PHP
<?php
$string = 'ab cd ab cd ab';
$string = ' '.$string; // because the while loop below won't run if we find the first match in position 0
$find = 'ab';
$find_length = strlen($find);
$offset = 1; // from this index the search of $find will start
// strpos function returns false when offset value equals to string length, but returns error for more than that
while($find_position = strpos($string, $find, $offset))
{
echo '<b>'.$find.'</b> is found at '.$find_position.'<br/>';
$offset = $find_position + $find_length;
}
?>
$string = 'ab cd ab cd ab';
$string = ' '.$string; // because the while loop below won't run if we find the first match in position 0
$find = 'ab';
$find_length = strlen($find);
$offset = 1; // from this index the search of $find will start
// strpos function returns false when offset value equals to string length, but returns error for more than that
while($find_position = strpos($string, $find, $offset))
{
echo '<b>'.$find.'</b> is found at '.$find_position.'<br/>';
$offset = $find_position + $find_length;
}
?>
Comments
Post a Comment