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;
}
?>

Comments

Popular posts from this blog

Timus 1209. 1, 10, 100, 1000... accepted solution in C

Timus Problem 1086. Cryptography Accepted Solution in C

Timus 1083. Factorials!!! Accepted Solution in C