I have problems with pattern.
I need to process some text for example:
<div>{text1}</div><span>{text2}</span>
After the process I need to get in place of {text1} and {text2} some words from dictionary.
I’m preparing ui interface for diffrent languages.
This is in PHP. For now I have something like this but this doesn’t work:
function translate_callback($matches) {
global $dict;
print_r($matches);
return 'replacement';
}
function translate($input) {
return preg_replace_callback('/(\{.+\})/', 'translate_callback', $input);
}
echo translate('<div>{bodynum}</div><span>{innernum}</span>');
This is test scenarion but I can’t find the way to define pattern because this one in code match
{bodynum}</div><span>{innernum}
but I want pattern that will match
{bodynum} and then {innernum}
Can somebody help me with this. Thanks.
The Solution:
To match any character between { and }, but don’t be greedy – match the shortest string which ends with } (the ? stops + being greedy).
So the pattern now looks like: ‘/{(.+?)}/’ and is exacly what I want.
As you correctly note in the comments, you can use an ungreedy match to stop at the first closing brace rather than the last:
As Damien notes, you can also use the
/Umodifier to make all matches ungreedy by default.Alternatively, you could restrict the set of characters allowed between the braces to some set that does not include
}:or even:
which allows only word characters between the braces. This might (or might not) be slightly more efficient than using ungreedy matching, due to the way the PCRE engine works. In practice, of course, there’s unlikely to be any observable difference.