Page 1 of 1

Regex PREG_REPLACE_EVAL question

Posted: Sun Dec 07, 2008 6:06 am
by Tommaso
Hi, am quite new to PHP and I am having a problem with a regular expression.

I have a expression with where $pattern = "/something/e"

and i am trying to evaluate preg_replace($pattern, "$this->myInnerClassFunction(\\0)",$replaceMe)

and it is not finding the function myInnerClassFunction since i am using $this. It would be great if someone could tell me what the proper syntax for using $this-> in a preg_replace. Thanks in advance for the help.

Re: Regex PREG_REPLACE_EVAL question

Posted: Tue Dec 09, 2008 1:52 pm
by prometheuzz
You can't pass parameters to that method: the matches from your regex are passed automatically and since the method is inside a class (opposed to a static context), you will have to pass an Array. And lastly, you need to use the preg_replace_callback(...) function.
And to finish: all these remarks combined in an example where all the 'm' and 'o' characters from your screen name are wrapped around parenthesis:

Code: Select all

class Person {
    
    var $name = 'Tommaso';
    
    function my_inner_class_function($matches) {
        return "($matches[0])";
    }
    
    function foo($pattern) {
        return preg_replace_callback($pattern, Array($this, "my_inner_class_function"), $this->name);
    }
}
 
$you = new Person;
 
echo $you->foo('/[mo]/');
HTH