MTVS
MTVS

Reputation: 2096

preg_replace_callback, callback's return value don't replace the matched string

In the following snippet

Why doesn't bar replace foo?

$subject = "Hello foo";

preg_replace_callback(
    '/\bfoo\b/i',

    function ($match)
    {
        return 'bar';
    },

    $subject
 );

 echo $subject;

Upvotes: 1

Views: 922

Answers (1)

tmuguet
tmuguet

Reputation: 1165

preg_replace_callback does not modify $subject but returns the new string:

The following code should work:

$subject = "Hello foo";

echo preg_replace_callback(
    '/\bfoo\b/i',

    function ($match)
    {
        return 'bar';
    },

    $subject
 );

Upvotes: 3

Related Questions