How to find the starting index of all occurrences of a word in a string in PHP

1 Answer

0 votes
/*
    Find all starting indices of a word inside a larger text.
    This function uses strpos in a loop. The function is efficient
    and implemented in optimized C code inside PHP's engine.
*/
function findAllOccurrences(string $text, string $word): array
{
    $indices = [];

    // Searching for an empty word is meaningless
    if ($word === '') {
        return $indices;
    }

    $pos = strpos($text, $word); // First occurrence

    while ($pos !== false) {
        $indices[] = $pos;       // Store the index

        /*
            Search again starting one character after the previous match.
            This allows detection of overlapping matches.
        */
        $pos = strpos($text, $word, $pos + 1);
    }

    return $indices;
}

// Example usage
$text = "the quick brown fox jumps over the lazy dog. the fox is clever.";
$word = "the";

echo "Text: $text\n";
echo "Word: \"$word\"\n\n";
echo "Occurrences at indices:\n";

foreach (findAllOccurrences($text, $word) as $index) {
    echo $index . "\n";
}



/*
run:

Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"

Occurrences at indices:
0
31
45

*/

 



answered Aug 30 by avibootz

Related questions

...