I would like to know if there is a simple way to use the matched pattern in a preg_replace
as an index for the replacement value array.
e.g.
preg_replace("/\{[a-z_]*\}/i", "{$data_array[\1]}", $string);
Search for a placeholder like {xxx}
and replace it with the value in $data_array['xxx']
, where xxx
is the matched text inside the curly braces.
But this expression does not work as it's invalid php.
I have written the following function, but I'd like to know if it is possible to do it simply. I could use a callback, but how would I pass the $data_array
to it too?
function mailmerge($string, $data_array, $tags='{}')
{
$tag_start=$tags[0];
$tag_end =$tags[1];
if( (!stristr($string, $tag_start)) && (!stristr($string, $tag_end)) ) return $string;
while(list($key,$value)=each($data_array))
{
$patterns[$key]="/".preg_quote($tag_start.$key.$tag_end)."/";
}
ksort($patterns);
ksort($data_array);
return preg_replace($patterns, $data_array, $string);
}
preg_replace_callback()
– Innervate/e
modifier (your curly string expression needed array key quotes still). It's outlawed now however, and has limited advantages overp_r_callback
. Take care that you also need paranthesis for a capture group/\{([a-z_]*)\}/i
. – Fonda