代码之家  ›  专栏  ›  技术社区  ›  thesunneversets

和Preg在一起有点过头了

  •  1
  • thesunneversets  · 技术社区  · 14 年前

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

    我想对字符串进行查找和替换,用正确的数据替换每个标记,可能使用preg_replace_回调。不过,我是个新手,所以这是我最近的一次了,我相信它的速度慢得可笑,效率低:

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

    有谁能帮我想出更好的办法来完成这件事吗?

    1 回复  |  直到 14 年前
        1
  •  0
  •   bcosca    14 年前
    /\[\s*\'([^\']*)\'\s*\]\s*:\s*\[\s*\'([^\']*)\'\s*\]/