1

我有一个包含 html 和“标签”的字符串,格式为 [realtor:name] 或 [office:phone]。我有一个(CakePHP 生成的)数据库数据数组,这样可以在 $data['Realtor']['name'] 和 $data['Office']['phone' 的办公室电话中找到房地产经纪人的姓名]。

我想对字符串进行查找和替换,用正确的数据替换每个标签,可能使用 preg_replace_callback。不过,我有点新手,所以这是我所拥有的最接近的,而且我敢肯定它非常缓慢且效率低下:

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;
}

任何人都可以帮助我提出一些更好的方法来完成这项工作吗?

4

1 回答 1

0
/\[\s*\'([^\']*)\'\s*\]\s*:\s*\[\s*\'([^\']*)\'\s*\]/
于 2010-11-10T21:48:24.313 回答