php - How to preg_replace content between {{ }} -
the following code replace content between {{ }}
. example use {{example}} load custom text db replace content in html output. works @ times not , unsure why. maybe in same line if use 2 {{one}} , {{two}} .. thought maybe doing preg_replace
wrong.
function translate($tagname){ global $$tagname; return $$tagname; } function replacetags($body){ $body = preg_replace('!{{(.*?)}}!uei', "''.translate('$1').''", $body); return $body; }
you should drop u
modifier, turn ungreedy (.*?)
greedy, , not want.
also, e
modifier deprecated in php 5.5.0. use preg_replace_callback instead:
$firstname = 'jane'; $lastname = 'doe'; function translate($tagname){ global $$tagname; return $$tagname; } function translatematch($matches) { return translate($matches[1]); } function replacetags($body){ $body = preg_replace_callback('!{{(.*?)}}!i', 'translatematch', $body); return $body; } echo replacetags("hello, {{firstname}} {{lastname}}!"), php_eol;
output:
hello, jane doe!
Comments
Post a Comment