php preg_replace 忽略内容中的 $n
我当前的正则表达式是 /[$]([a-zA-Z0-9_\-\,:]*)[$]/
这将允许我为我们的 CMS 替换如下所示的字符串:
$ContentArea1$
$blog:PostTitle$
但是,当我们的内容以美元为单位时,preg_replace
会去掉价格的第一部分,例如 $15 $1 $2 等
我该如何制作 preg_replace
代码> 忽略内容内的价格?
<?
$message = 'Below is an example for the content replacement<br/><br/><br/>$ContentArea1$';
$newMessage = '<h2>Website Coming soon</h2>
<p>
Are new website will be online soon.</p>
<p>
Price: $2.50</p>
<h2>
Twitter Feed</h2>
';
echo preg_replace('/[$]ContentArea1[$]/',$newMessage,$message);
?>
My current regex is /[$]([a-zA-Z0-9_\-\,:]*)[$]/
and this will allow me to replace strings like the following for our CMS:
$ContentArea1$
$blog:PostTitle$
However when we have content which has prices in dollars preg_replace
gets rid of the first part of the price e.g. $15 $1 $2 etc
How can I make preg_replace
ignore prices within the content?
<?
$message = 'Below is an example for the content replacement<br/><br/><br/>$ContentArea1
;
$newMessage = '<h2>Website Coming soon</h2>
<p>
Are new website will be online soon.</p>
<p>
Price: $2.50</p>
<h2>
Twitter Feed</h2>
';
echo preg_replace('/[$]ContentArea1[$]/',$newMessage,$message);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以扩展正则表达式以包含
$
后跟数字,以便价格值中的$
不终止:You can extend your regular expression to include
$
followed by numbers so that the$
in price values are non-terminating:我不确定我是否正确理解您的问题,但我有三种可能的解决方案:
更改正则表达式,以便它仅匹配不以数字开头的变量:
[$]([a-zA-Z_\-\,:][a-zA-Z0-9_\-\,:]*)[$]
将其更改为仅匹配包含冒号的变量:
[$]([a-zA-Z0-9_\-\,]*:[a-zA-Z0-9_\-\,]*)[$]
您还可以使用函数
preg_replace_callback
或/e
修饰符来调用仅替换有效变量名称的自定义 PHP 函数。I'm not sure, if I understand your problem right but I have three possible solutions:
Change the regex, so that it matches only variables that don't start with numbers:
[$]([a-zA-Z_\-\,:][a-zA-Z0-9_\-\,:]*)[$]
Change it to match only variables that contain a colon:
[$]([a-zA-Z0-9_\-\,]*:[a-zA-Z0-9_\-\,]*)[$]
You could also use the function
preg_replace_callback
or the/e
modifier to call a custom PHP function that only replaces valid variables names.我已经找到了如何允许 $1.99 显示在替换 $ContentArea1$ 或我使用以下函数的任何其他变量的内容中。
现在,我可以在内容中显示 $ 符号,这就是所需的。
来源:http://www.procata。 com/blog/archives/2005/11/13/two-preg_replace-escaping-gotchas/
感谢您的所有回答和评论
I have found out how to allow $1.99 to be displayed in the content that is replacing $ContentArea1$ or any other variable I have using the following function.
This now allows me to display $ symbols in the content which is what was required.
Source: http://www.procata.com/blog/archives/2005/11/13/two-preg_replace-escaping-gotchas/
Thanks for all of your answers and comments
感谢您发布问题的基本示例,现在很清楚您的问题是什么了:)
另一个简单的解决方案是使用
str_replace
而不是preg_replace
:Thanks for posting the basic example of your problem, now it's clear what your problem was :)
Another simple solution would be to use
str_replace
instead ofpreg_replace
: