Search code examples
phppcrepreg-replace-callback

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;

Solution

  • 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
     );