You could search and replace the %var
patterns using preg_replace
and the e
modifier, which makes the replacement being evaluated:
<?php
$my_str = "My String";
$str = "Foo %my_str bar";
$str = preg_replace("/%([A-Za-z_]+)/e", "$\\1", $str);
echo $str;
?>
Here preg_replace
will find %my_str
, \1
contains my_str
and "$\\1"
(the backslash needs to be escaped) becomes the value of $my_str.
However, it would maybe be cleaner to store your replacement strings in an associative array:
<?php
$replacements = array(
"my_str" => "My String",
);
$str = "Foo %my_str bar";
$str = preg_replace("/%([A-Za-z_]+)/e", '$replacements["\\1"]', $str);
echo $str;
?>