Reputation: 26281
I have a function that parses some text, and replaces any tags that are surrounded by "{
and }"
with values in an array.
function parse($template, array $values) {
return preg_replace_callback('/\{"{\ (\w+)\ \}\"/',function ($matches) use ($values) {
return isset($values[$matches[1]])?$values[$matches[1]]:$matches[0];
},
$template);
}
How can it be modified to do the same, but also use a second deliminator? Specifically, I also which it to replace tags surrounded by '{
and }'
Upvotes: 0
Views: 44
Reputation: 214949
A better option is to list possible delimiters explicitly:
$re = <<<RE
/
"{ (\w+) }"
|
'{ (\w+) }'
/x
RE;
(using extended syntax for readability). The actual captured group will be at the end of the matches
array:
preg_replace_callback($re, function ($matches) use ($values) {
$word = end($matches);
if (isset($values[$word])) etc....
},
This verbosity will pay off once you introduce more delimiters, especially non-symmetric ones, for example:
$re = <<<RE
/
"{ (\w+) }"
|
'{ (\w+) }'
|
<{ (\w+) }>
|
{{ (\w+) }}
/x
RE;
Upvotes: 1
Reputation: 16214
Something like this (did not check it) /\{("|\'){\ (\w+)\ \}\1/
or /\{(["\']){\ (\w+)\ \}\1/
Upvotes: 1