PHP - preg_用数组项替换括号中的项
我有一个数组:
array('id' => 'really')
我有一个字符串:
$string = 'This should be {id} simple.';
我想最终得到:
This should be really simple.
我有一个可以与 {id} 方面一起使用的正则表达式,但我很难做我想做的事情。
/{([a-zA-Z\_\-]*?)}/i
{id} 可以是任何内容,{foo} 或 {bar} 或任何与我的正则表达式匹配的内容。
我确信目前我没有找到一个简单的解决方案。
谢谢,
贾斯汀
I have an array:
array('id' => 'really')
I have a string:
$string = 'This should be {id} simple.';
I want to end up with:
This should be really simple.
I have a regular expression that will work with the {id} aspect, but I am having a hard time doing what I want.
/{([a-zA-Z\_\-]*?)}/i
{id} could be anything, {foo} or {bar} or anything that matches my regular expression.
I am sure that there is a simple solution that is escaping me at the moment.
Thanks,
Justin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
str_replace 比 preg_replace 更快,试试这个:
str_replace is faster then preg_replace, try this:
您可以将
preg_replace
与e
修饰符一起使用,如下所示:Ideone Link
使用
e
修饰符,您可以在preg_replace
的替换部分中使用任何PHP表达式。现在为什么你的正则表达式
/{([a-zA-Z\_\-])*?}/i
不起作用?您已将
*?
放在捕获括号( )
之外,因此您仅捕获{ }
中找到的单词的第一个字符。另请注意,您没有转义
{
和}
,它们是用于指定范围量词{num}
,的正则表达式元字符{最小值,最大值}
。但在您的情况下,不需要转义它们,因为正则表达式引擎可以从上下文推断{
和}
不能用作范围运算符,因为它们内部没有所需格式的数字,因此按字面意思对待它们。You can use the
preg_replace
withe
modifier as:Ideone Link
Using the
e
modifier you can have any PHP expression in the replacement part ofpreg_replace
.Now why did your regex
/{([a-zA-Z\_\-])*?}/i
not work?You've put
*?
outside the capturing parenthesis( )
as a result you capture only the first character of the word found in{ }
.Also note that you've not escaped
{
and}
which are regex meta-character used for specifying range quantifier{num}
,{min,max}
. But in your case there is no need to escape them because the regex engine can infer from the context that{
and}
cannot be used as range operator as they are not having numbers in required format inside them and hence treats them literally.preg_replace_callback
有一个回调选项使这种事情成为可能。如果您不想使用全局变量,请创建一个类并使用
array($object, 'method')
回调表示法。preg_replace_callback
has a callback option which make that kind of things possible.If you don't want to use the global variable create an class and use the
array($object, 'method')
callback notation.