Find all occurrences of a substring in a string with PHP

PHP stripos (or mb-stripos) finds the position of the first occurrence of a (case-insensitive) substring in a string. How to find all occurrences?

Here is a solution:

<?php
/**
 * mb_stripos all occurences
 * based on http://www.php.net/manual/en/function.strpos.php#87061
 *
 * Find all occurrences of a needle in a haystack (case-insensitive, UTF8)
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function mb_stripos_all($haystack, $needle) {

        $s = 0;
        $i = 0;

        while(is_integer($i)) {

                $i = mb_stripos($haystack, $needle, $s);

                if(is_integer($i)) {
                        $aStrPos[] = $i;
                        $s = $i + mb_strlen($needle);
                }
        }

        if(isset($aStrPos)) {
                return $aStrPos;
        } else {
                return false;
        }
}
?>

Your comments are welcome!


Never Miss A Post!

Subscribe to our free NewsLetter