PHP Find all occurrences of a substring in a string

PHP Find all occurrences of a substring in a string

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP Find all occurrences of a substring in a string

The strpos function is ubiquitous in PHP, but its behavior often trips up developers who need more than just the first match. When you call strpos($haystack, $needle), it returns the position of the very first occurrence or false if the needle isn't found. While this works perfectly for a simple lookup, parsing an HTML document to extract data after every instance of a specific string—like <code>asdf</code> in your case—requires a different approach. You cannot simply loop while strpos returns true; doing so without updating the search start position will result in an infinite loop or missed results.

To retrieve all character positions, you must manually advance the search window after each find. The standard pattern involves a while loop that checks for a match and then moves the starting point of the next iteration past the current match. However, there is a critical nuance: strpos returns the offset of the first character of the match. If your goal is to extract data immediately following the string, you need to account for the length of the matched substring.

Here is a robust implementation that handles multiple occurrences correctly:

$haystack = '<div>asdf content 1</div> <div>asdf content 2</div>';
$needle = 'asdf';
$offset = 0;
$positions = [];

while (($pos = strpos($haystack, $needle, $offset)) !== false) {
    $positions[] = $pos;
    
    // Move the offset past the current match to find the next one.
    // If you wanted overlapping matches (e.g., finding 'aba' in 'ababa'), 
    // you would only increment by 1 here, but for distinct substrings, use strlen.
    $offset = $pos + strlen($needle);
}

// Output: Array ( [0] => 6 [1] => 23 )
print_r($positions);

In this example, the loop finds the first asdf, records its position (6), and then sets the $offset to the character immediately following that instance. The next iteration searches from that new offset onward. This prevents the function from re-scanning the same characters it has already processed.

Handling Overlapping Matches

There is a scenario where this standard approach might feel insufficient: overlapping substrings. If your target string is aba and your input is ababa, a naive search starting at position 6 (length of aba) would miss the second aba which starts at position 2 if you were scanning backwards, or it might behave unexpectedly depending on how you define "occurrence."

For non-overlapping matches, advancing by strlen($needle) is efficient and correct. If you specifically need to find overlapping instances—for example, finding every occurrence of a regex-like pattern where the needle can start inside a previous match—you must increment the offset by only 1 instead of the full string length:

// Find overlapping occurrences
$offset = 0;
$positions = [];

while (($pos = strpos($haystack, $needle, $offset)) !== false) {
    $positions[] = $pos;
    // Increment by 1 to allow overlaps
    $offset = $pos + 1; 
}

Performance Considerations for Large HTML Documents

When parsing large HTML documents, the manual while loop with strpos is generally acceptable, but it has a linear time complexity relative to the string length and the number of matches. If you are dealing with massive files where performance is critical, or if you need regular expression capabilities (like case-insensitivity or character classes) alongside position tracking, switching to the PCRE functions might be worth considering.

Using preg_match_all can retrieve all matches in a single pass, though it returns match arrays rather than raw offsets unless configured carefully with PREG_OFFSET_CAPTURE. This function is often cleaner if you also need the matched content itself:

$matches = [];
preg_match_all('/asdf/', $haystack, $matches, PREG_OFFSET_CAPTURE);

foreach ($matches[0] as $match) {
    // $match[0] is the string "asdf"
    // $match[1] is the position
    echo "Found at: {$match[1]}\n";
}

Parsing HTML Context

Remember that your source material involves parsing an HTML document. If the string asdf appears inside a tag or as part of a larger attribute, simple substring matching works fine for position tracking but might yield confusing results if you intend to extract specific DOM elements later. In such cases, relying on a dedicated HTML parser is usually safer than manipulating raw strings, even though finding the character offset via strpos remains valid for your immediate need.

If you are building a larger application where this pattern repeats frequently, consider wrapping this logic in a utility class or service. Laravel provides robust tools for string manipulation and DOM traversal; if you are already using the framework, check out resources like https://laravelcompany.com to see how modern frameworks abstract these low-level string operations into more expressive helpers.

Our network