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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
/**
 * mb_stripos all occurences
 *
 * 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;
        }
}
?>