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.
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
$thisobject, 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….
The user comments in the PHP manual are one of the best things about PHP, period!
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
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.