PHP Find all occurrences of a substring in a string

Its better to use substr_count . Check out on php.net


You can call the strpos function repeatedly until a match is not found. You must specify the offset parameter.

Note: in the following example, the search continues from the next character instead of from the end of previous match. According to this function, aaaa contains three occurrences of the substring aa, not two.

function strpos_all($haystack, $needle) {
    $offset = 0;
    $allpos = array();
    while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
        $offset   = $pos + 1;
        $allpos[] = $pos;
    }
    return $allpos;
}
print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 8
    [3] => 9
    [4] => 16
    [5] => 17
)

Without using regex, something like this should work for returning the string positions:

$html = "dddasdfdddasdffff";
$needle = "asdf";
$lastPos = 0;
$positions = array();

while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
    $positions[] = $lastPos;
    $lastPos = $lastPos + strlen($needle);
}

// Displays 3 and 10
foreach ($positions as $value) {
    echo $value ."<br />";
}

Tags:

Php

String