PHP preg_replace regex question
I need some help figuring out an regular expression. In my script I have a certain line with placeholders. W开发者_如何转开发hat 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
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
You need to use either the /e
modifier to parse the replacement to eval
, or use preg_replace_callback().
eg.
$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);
精彩评论