Dougal Campbell's geek ramblings

WordPress, web development, and world domination.

A PHP Question

Okay, here’s a question for some of you PHP OOP gurus out there: How can you use the preg_replace_callback() function from inside of a class method? I even tried using create_function() to make a self-contained lambda, but it seemed like it couldn’t access class properties via the $this variable.

For example:


$result = preg_replace_callback(
  '/({{(.*)}})/',  /* pattern */
  create_function(
    '$m', /* param. gets matches array from preg_replace_callback */
    'return $this->myarr[$m[2]];' /* code. just looks up the match in an array */
  ),  /* callback function */
  $mystring  /* original string */
);

This should replace text like {{foo}} with the corresponding $myclass->myarr['foo'] value set in the class. But I couldn’t get it to work using preg_replace_callback(). Instead, I manually extracted the keys and values of the $myclass->myarr array, and passed them to a preg_replace() call. But that just doesn’t seem as elegant.

About Dougal Campbell

Dougal is a web developer, and a "Developer Emeritus" for the WordPress platform. When he's not coding PHP, Perl, CSS, JavaScript, or whatnot, he spends time with his wife, three children, a dog, and a cat in their Atlanta area home.
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

4 Responses to A PHP Question

Leave a Reply