与 Preg 的相处有点让我难以理解

发布于 2024-10-02 12:28:06 字数 837 浏览 0 评论 0原文

我有一个包含 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;
}

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风流物 2024-10-09 12:28:06
/\[\s*\'([^\']*)\'\s*\]\s*:\s*\[\s*\'([^\']*)\'\s*\]/
/\[\s*\'([^\']*)\'\s*\]\s*:\s*\[\s*\'([^\']*)\'\s*\]/
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文