1

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?

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Why is it that s is not also returned as a parenthesized capture group?
your subject string doesn't an s and you have a ? making the group optional. If you moved the ? inside of the parenthesis, the group would always exist, but be blank or s depending on whether it is there.
Oh, I'm swapping between my own code and the example code here. My mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.