Search code examples
phpregexpreg-replacepreg-replace-callback

preg_replace_callback returns duplicate values


I'm trying to understand the preg_replace_callback function. Inside my callback, I am getting the matched string twice instead of the just one time it appears in the subject string. You can go here and copy/paste this code into the tester and see that it returns two values when I would expect one.

preg_replace_callback(
    '"\b(http(s)?://\S+)"', 
    function($match){           
        var_dump($match);
        die();
    },
    'http://a'
);

The output looks like this:

array(2) { [0]=> string(8) "http://a" [1]=> string(8) "http://a" }

The documentation mentions returning an array if the subject is an array, or a string otherwise. What's happening?


Solution

  • You have a full pattern match \b(http(s)?://\S+) in $match[0] and a match for the parenthesized capture group (http(s)?://\S+) in $match[1].

    In this case just use $match[0] something like:

    $result = preg_replace_callback(
        '"\b(http(s)?://\S+)"', 
        function($match){           
            return $match[0] . '/something.php';
        },
        'http://a'
    );
    

    Replaces http://a with http://a/something.php.