Search code examples
phpregexpreg-replace-callback

PHP preg_replace_callback not replacing my "matches"


Why is this returning the original string and not the edited string?

Original String:

I cant believe Ed ate [-food-] for breakfast.

Replace:

preg_replace_callback('/\[\-[a-zA-Z0-9_]\-\]/', 'tag_func', $email_body);

function tag_func($matches){
     $matches[0] = 'tacos';
     return $matches[0];
}

Outcome Desired String:

I cant believe Ed ate tacos for breakfast.

This is my warning I'm getting:

preg_replace_callback(): Requires argument 2, 'tag_func', to be a valid callback 

Solution

  • You forgot to add a +, so that it should match multiple characters:

    preg_replace_callback('/\[-[a-z\d_]+-\]/i', 'tag_func', $email_body);
    //                                 ^
    

    See it here in action: http://codepad.viper-7.com/f94VPy


    If you're running 5.3, you can pass it an anonymous function directly:

    preg_replace_callback('/\[-[a-z\d_]+-\]/i', function () {
        return 'tacos';
    }, $email_body);
    

    Here's the demo: http://codepad.viper-7.com/NGBAIh