正则表达式:匹配并替换“AB ABC D”中的 ABC
我需要有关此片段的建议
$text = preg_replace('|(A.*)?A(.*)C|', '$1foo$2bar', $text);
这将匹配“AB ABC D”中的 ABC,并将其替换为“AB fooBbar D”; 正如你所看到的,这也匹配开头的“AB”部分,我必须在替换字符串中用 $1 重复它,以免丢失它。
这是获得这样结果的最佳方法吗?
是否有一个标志 X 可以
$text = preg_replace('|A(.*)C|X', 'foo$1bar', $text);
产生相同的结果?
我希望我已经说清楚了
谢谢!
编辑:将 A、B、C 视为任意字符的原子字符串,它们也可以包含空格此外
,所提供的示例实际上有错误,因为它仅匹配“ABC”中的第二个“ABC” ABC”。
EDIT2:抱歉,我可能对这个问题解释得很糟糕。 重点是我想匹配两个 A,C 字符串之间的 whatever ,这样匹配中就没有子字符串 A
再次感谢
I need advice on this snippet
$text = preg_replace('|(A.*)?A(.*)C|', '$1foo$2bar', $text);
This will match ABC in "AB ABC D", and replace it with "AB fooBbar D"; as you can see this matches the "AB " part at the beginning as well, which I have to repeat in the replacement string with $1, in order not to lose it.
Is this the best way to get such a result?
Is there a flag X such that
$text = preg_replace('|A(.*)C|X', 'foo$1bar', $text);
produces the same result?
I hope I've been clear
Thank you!
EDIT: Consider A,B,C as atomic strings of arbitrary characters, they can contain whitespaces as well
Also, the presented example is in fact buggy, as it matches only the second "ABC" in "ABC ABC".
EDIT2: I'm sorry, I've probably explained the problem very badly. The point is I'd want to match whatever is between two A,C string, so that there is no substring A in the match
Again thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
\S
匹配非空白字符,因此您不会替换不同的单词。看到OP的一些评论后,我会冒险另一个猜测:
How about this:
The
\S
matches a non-whitespace character, so you won't replace across different words.After seeing some of the OP's comments, I'll hazard another guess:
使用
*
量词的非贪婪版本:Use the non-greedy version of the
*
quantifier :由于问题已得到澄清,请尝试以下表达式:
示例:
As the question has been clarified, try this expression:
An example: