PHP Find all occurrences of a substring in a string

php, string

Solution

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 />";
}

Problem

I need to parse an HTML document and to find all occurrences of string `asdf` in it. I currently have the HTML loaded into a string variable. I would just like the character position so I can loop through the list to return some data after the string. The `strpos` function only returns the first occurrence. How about returning all of them?

Original source

Related problems