Take the 2-minute tour ×

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.

Can anybody help me out?

Br, Paul Peelen

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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: Is there anything like RegexBuddy in the open source world?

share|improve this answer
Thnx. It worked perfectly. When I get the time I'll check your links out. Should really get going with regex. –  Paul Peelen Feb 19 '11 at 1:03
add comment

You need to use either the /e modifier to parse the replacement to eval, or use preg_replace_callback().


$sString = preg_replace("#\{\{(*.?)\}\}#e", 'echoText("$2")', $sString);

But the $this will cause problems there, if you are using 5.3+ you could use a closure to create a function to cope with that, or create a callback:

$sString = preg_replace_callback("#\{\{(*.?)\}\}#", array($this, 'echoText'), $sString);

$this->echoText() would have to be modified to catch the match array rather than the string in that case.

Or with an anonymous function:

$sString = preg_replace_callback("#\{\{(*.?)\}\}#", function ($matches) {
               return $this->echoText($matches[1]);
           }, $sString);
share|improve this answer
add comment

Your Answer


