<tutorialjinni.com/>

Find all occurrences of a String in a String in PHP

Posted Under: PHP, Snippets on Aug 16, 2018
Find all occurrences of a String in a String in PHP
This PHP snippet will list all indexes of a sub-string in parent string.
function findAllSubStringIndexes($haystack, $needle) {
    $lastMatch = 0;
    $indexes = array();
    while (($lastMatch = strpos($haystack, $needle, $lastMatch))!== false) {
        $indexes[] = $lastMatch;
        $lastMatch = $lastMatch + strlen($needle);
    }
    return $indexes;
}
$indexes= findAllSubStringIndexes("You have no need to light a night-light, On a light night like tonight", "light");
print_r($indexes);
Sample output would be
Array
(
    [0] => 20
    [1] => 34
    [2] => 46
)


imgae