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.
4 Responses to A PHP Question