【发布时间】:2013-04-02 20:05:40
【问题描述】:
刚刚完成这个功能。基本上,它假设查看一个字符串并尝试找到任何占位符变量,这些变量将放置在两个大括号{} 之间。它获取大括号之间的值,并使用它来查看应该匹配键的数组。然后它将字符串中的大括号变量替换为匹配键的数组中的值。
但它有一些问题。首先是当我var_dump($matches) 时,它会将结果放入一个数组中,在一个数组内。所以我必须使用两个foreach() 才能获得正确的数据。
我也觉得它很重,我一直在检查它,试图让它变得更好,但我有点难过。我错过了哪些优化?
function dynStr($str,$vars) {
preg_match_all("/\{[A-Z0-9_]+\}+/", $str, $matches);
foreach($matches as $match_group) {
foreach($match_group as $match) {
$match = str_replace("}", "", $match);
$match = str_replace("{", "", $match);
$match = strtolower($match);
$allowed = array_keys($vars);
$match_up = strtoupper($match);
$str = (in_array($match, $allowed)) ? str_replace("{".$match_up."}", $vars[$match], $str) : str_replace("{".$match_up."}", '', $str);
}
}
return $str;
}
$variables = array("first_name"=>"John","last_name"=>"Smith","status"=>"won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';
echo dynStr($string,$variables);
//Would output: 'Dear John Smith, we wanted to tell you that you won the competition.'
【问题讨论】:
-
请向我们提供数据样本($str & $vars)
-
你的方法效率很低。考虑一种替代方法:a) 使用
preg_replace_callback从$vars返回匹配的令牌值,而无需一百万次str_replace调用; b) 转换$vars中的每个条目以包含前导/后括号,然后将$vars输入strtr。 -
您这样做是为了学习还是为了生产?如果用于生产,您可能需要查看模板库,例如
smarty -
@DCoder:你能提供一些例子吗?我被你说的弄糊涂了。
-
@dm03514 它是用于生产的,但它就像初稿一样。不是最终产品。它也不适用于模板。这是一份时事通讯。
标签: php preg-match