I have a string containing html and “tags” in the form [realtor:name] or [office:phone]. I have a (CakePHP-generated) array of database data, such that the realtor’s name can be found in $data[‘Realtor’][‘name’] and the office phone at $data[‘Office’][‘phone’].
I want to do a find-and-replace on the string, replacing each tag with the correct data, possibly using preg_replace_callback. I’m a bit of a newbie, though, so this is the closest I’ve got, and I’m sure it’s ridiculously slow and inefficient:
function template_swap($html, $data) {
preg_match_all('/\[(.*):(.*)\]/', $html, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (isset( $data[ ucfirst($match[1]) ] )) {
if (array_key_exists( $match[2], $data[ ucfirst($match[1]) ] )) {
$html = str_replace(
$match[0],
$data[ ucfirst($match[1]) ][ $match[2] ],
$html
);
}
}
}
return html;
}
Can anyone help me out with some ideas on better ways to get this done?
1 Answer