正则表达式和php
假设我有一个像这样的字符串:
$string = 'The /*quick*/ brown /*fox*/ jumped over the lazy /*dog*/.';
如何使用正则表达式来查找 /* */ 的出现并像这样替换每个值:
/*quick*/ with the value of $_POST['quick']
/*fox*/ with the value of $_POST['fox']
/*dog*/ with the value of $_POST['dog']
我已尝试使用以下模式使用 preg_replace: ~/\*(.+ )\*/~e
但这似乎对我不起作用。
Say I have a string like this:
$string = 'The /*quick*/ brown /*fox*/ jumped over the lazy /*dog*/.';
How can I use a regular expression to find the occurrences of /* */ and replace each value like so:
/*quick*/ with the value of $_POST['quick']
/*fox*/ with the value of $_POST['fox']
/*dog*/ with the value of $_POST['dog']
I have tried with preg_replace using this pattern: ~/\*(.+)\*/~e
But it does not seem to be working for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模式
(.+)
太贪婪了。它会找到最长的匹配,即quick*/ Brown /*fox*/跳过了lazy /*dog
,所以它不会工作。如果
/*
和*/
之间不会出现*
,则使用:否则,使用惰性量词:
示例:http://www.ideone.com/hVUNA。
The pattern
(.+)
is too greedy. It will find the longest match i.e.quick*/ brown /*fox*/ jumped over the lazy /*dog
, so it won't work.If there will be no
*
appear between/*
and*/
, then use:Otherwise, use a lazy quantifier:
Example: http://www.ideone.com/hVUNA.
您可以概括这一点(PHP 5.3+,动态函数):
如果您想对替换内容进行精细控制。否则,KennyTM 已经解决了这个问题。
问候
rbo
You can generalize this (PHP 5.3+, dynamic functions):
if you want to have fine control over what gets replaced. Otherwise, KennyTM already solved this.
Regards
rbo