PHP:用 preg_replace 替换范围内的特定字符

发布于 2024-09-07 09:43:48 字数 345 浏览 3 评论 0原文

假设我正在尝试将两个 [lol] 标签内的每个“A”字符替换为“B”。

例如:

“[lol]It'sgreatA确实是A[/lol]”

将变成

“[lol]It'sgreatB确实是B[/lol]”

我试图自己做点什么,但这是徒劳的。 我得到的最接近的是:

preg_replace("%(\[lol\])"."(.*?)([A]+?)(.*?)"."(\[/lol\])%s", "$1$2B$4$5", $haystack);

当然它不会这样工作......

我将不胜感激任何帮助!

谢谢!

Lets say I'm trying to replace every "A" character with a "B", inside two [lol] tags.

For example:

"[lol]It's greatA really isA[/lol]"

will become

"[lol]It's greatB really isB[/lol]"

I was trying to work something myself but it was in vain.
The closest i got is this:

preg_replace("%(\[lol\])"."(.*?)([A]+?)(.*?)"."(\[/lol\])%s", "$1$2B$4$5", $haystack);

of course it doesn't work this way...

I'll appreciate any assistance!

thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

尐偏执 2024-09-14 09:43:48
echo preg_replace(
    '/(?<=\[lol\]).*?(?=\[\\/lol\])/e',
    'str_replace("A", "B", "\\0")',
    'AAA sdf [lol]It\'s greatA really isA[/lol] AAAA ' .
        'sdfd [lol]It\'s greatA really isA[/lol] AA sf'
);

给出

AAA sdf [lol]It\'s greatB really isB[/lol] AAAA sdfd [lol]It\'s greatB really isB[/lol] AA sf
echo preg_replace(
    '/(?<=\[lol\]).*?(?=\[\\/lol\])/e',
    'str_replace("A", "B", "\\0")',
    'AAA sdf [lol]It\'s greatA really isA[/lol] AAAA ' .
        'sdfd [lol]It\'s greatA really isA[/lol] AA sf'
);

gives

AAA sdf [lol]It\'s greatB really isB[/lol] AAAA sdfd [lol]It\'s greatB really isB[/lol] AA sf
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文