正则表达式:匹配并替换“AB ABC D”中的 ABC

发布于 2024-07-13 20:48:56 字数 629 浏览 7 评论 0原文

我需要有关此片段的建议

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软糖 2024-07-20 20:48:56

怎么样:

$text = preg_replace('|A(\S*)C|', 'foo$1bar', $text);

\S 匹配非空白字符,因此您不会替换不同的单词。


看到OP的一些评论后,我会冒险另一个猜测:

$text = preg_replace('|A(B)C|', 'foo$1bar', $text);

How about this:

$text = preg_replace('|A(\S*)C|', 'foo$1bar', $text);

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:

$text = preg_replace('|A(B)C|', 'foo$1bar', $text);
冷情 2024-07-20 20:48:56

使用 * 量词的非贪婪版本:

$text = preg_replace('|(.*)(A.*?C)|', '$1foo$2bar', $text);

Use the non-greedy version of the * quantifier :

$text = preg_replace('|(.*)(A.*?C)|', '$1foo$2bar', $text);
安人多梦 2024-07-20 20:48:56

由于问题已得到澄清,请尝试以下表达式:

preg_replace('/(?:A)+(.+?)(?:C)+/', 'foo$1bar', $text)

示例:

$A = 'abc'; $B = '123'; $C = 'xyz';
$text = "$A$B$C $A$A$B$C $A$B$C$C";
echo preg_replace("/(?:$A)+(.+?)(?:$C)+/", 'foo$1bar', $text);

As the question has been clarified, try this expression:

preg_replace('/(?:A)+(.+?)(?:C)+/', 'foo$1bar', $text)

An example:

$A = 'abc'; $B = '123'; $C = 'xyz';
$text = "$A$B$C $A$A$B$C $A$B$C$C";
echo preg_replace("/(?:$A)+(.+?)(?:$C)+/", 'foo$1bar', $text);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文