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

  1. And as is typical, I found the answer just a few minutes after I posted the question. Apparently, instead of just a plain string for the function name, you can pass an array with a reference to the $this object, like so: preg_replace_callback($pattern,array(&$this,'funcname'),$string)

    I’m not sure where this is documented in the PHP manual, other than in user comments….

  2. Alex says:

    The user comments in the PHP manual are one of the best things about PHP, period!

  3. True, the user comments contain tons of extremely useful examples, hints, and gotchas. But it would be nice if that array trick for the function parameter was documented in the actual documentation 🙂

  4. visual says:

    The latest documentation does say “See also: ….. and the _callback_ type”, don’t know when that was added.
    Clicking that shows you how to use methods of instances as well as static methods of classes for callbacks.

Leave a Reply

%d bloggers like this: