与 Preg 的相处有点让我难以理解
我有一个包含 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)