0

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 
Dom
  • 858
  • 2
  • 11
  • 30

1 Answers1

1

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

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • This did not do it for me either. I have added the warning I keep getting. Any clues as to solving this puzzle of mine? – Dom Feb 01 '13 at 19:01
  • I straight up copied your demo and it didn't work... This is rather frustrating. – Dom Feb 01 '13 at 19:08
  • Great news, this in fact worked! I realized my problem and its the fact that I was calling a public static function. I ended up using array('Class Name', 'GetPlaceholderConverter') and it worked as well! – Dom Feb 01 '13 at 19:42