[英]PHP Preg_replace placeholders
Hi I'm writing something for handling my views an I need a preg_replace here, but i can't seem to get it working so I've scrapped the code. 嗨,我正在写一些东西来处理我的视图,这里我需要一个preg_replace,但是我似乎无法正常工作,所以我取消了代码。
the strings I am trying to replace are dynamic based on a template, eg 我要替换的字符串基于模板是动态的,例如
{{name}} is {{age}} years old
And the passed information into the function is an array eg 传递给函数的信息是一个数组,例如
array( 'name' => 'John Doe', 'age' => '27' );
The pattern I have so far is \\{{([a-zA-Z0-9]+)\\}}
however this only seems to match one pair of braces. 到目前为止,我的模式是
\\{{([a-zA-Z0-9]+)\\}}
但这似乎只匹配一对大括号。
I'm also having a problem looping through results in preg_match_all.. 我在遍历preg_match_all中的结果时也遇到了问题。
Thanks in advance 提前致谢
...however this only seems to match one pair of braces.
...但是,这似乎只匹配一对大括号。
You forgot the escape the second {
您忘记了第二个
{
/\{\{([a-zA-Z0-9]+)\}\}/
-^- -^-
In any case, try this regex, it's a bit shorter: 无论如何,请尝试使用此正则表达式,它会短一些:
/\{\{([^}]+)\}\}/
preg_replace_callback
seems like a good candidate. preg_replace_callback
似乎是一个不错的选择。
$str = "{{name}} is {{age}} years old";
$values = array( 'name' => 'John Doe', 'age' => '27' );
echo preg_replace_callback("/\{{([a-z0-9]+?)\}}/i", function ($result)
use ($values) {
if (isset($result[1])) {
return $values[$result[1]];
}
}, $str);
The main issue is that {{[az]+}}
will match from {{name ... age}}
. 主要问题是
{{[az]+}}
与{{name ... age}}
匹配。 Using the ?
使用
?
makes the +
reluctant so it only matches up to the first }
rather than the last. 使
+
不太愿意,因此它只匹配第一个 }
而不是最后一个。
Why don't you use sprintf
? 为什么不使用
sprintf
?
$template = '%s is %d years old';
$vars = array('name' => 'John Doe', 'age' => 27);
$output = sprintf($template, $vars['name'], $vars['age']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.