Search code examples
phpregexcallbackpreg-replaceplaceholder

Replace a double curly braced placeholder with a method call as the replacement parameter of preg_replace()


I need some help figuring out an regular expression. In my script I have a certain line with placeholders. What I want to do is I want to send every placeholder text a an function that translates it to what it should be.

E.g. my text is:

Lorem ipsum dolor sit {{AMETPLACEHOLDER}}, consectetur adipiscing elit.

I want the text AMETPLACEHOLDER to be send of to my function translateMe.

I am really bad in regex but gave it a try anyways. I don't get further than this:

$sString = preg_replace("(*.?)/\{{(*.?)}}(*.?)/", $this->echoText('\\2'), $sString);

Which off course doesn't work.


Solution

  • Using preg_replace_callback, you can specify a method like this:

     = preg_replace_callback("@{{(.*?)}}@", array($this, "echoText"), $txt)
    

    And the method could be:

     public function echoText($match) {
         list($original, $placeholder) = $match;   // extract match groups
         ...
         return $translated;
     }
    

    Btw, for designing regular expressions check out http://regular-expressions.info/ or some of the tools listed in: https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world