Search code examples
phpregexstringpreg-replace-callback

Why the argument that preg_replace_callback passes to the callback function is an array


This might be a stupid question but why preg_replace_callback puts every match in a single-element array and passes it to the callback function so I have to use $matches[0] to process a match, why doesn't it pass matches to the callback function as strings?


Solution

  • Because you can have capturing groups, and each element in the array would be what the capturing group captured. The element at index 0 is always the entire match.

    For example, given a regex that matches MM/DD/YYYY dates, you might put each segment of the date in its own capturing group, perhaps something naive like this:

    (\d{2})/(\d{2})/(\d{4})
    

    Then, you'd have a matches array similar to:

    [0] - MM/DD/YYYY
    [1] - MM
    [2] - DD
    [3] - YYYY