PHP:替换字符并进行例外(preg_replace)

发布于 2024-09-24 10:31:04 字数 572 浏览 0 评论 0原文

如何:

  • 使用 preg_replace() 替换单词中的字符,但 make 如果它们是以下内容的一部分则例外 某个词。
  • 将大写字符替换为 大写替换,即使 替换为小写,副 反之亦然。

示例:

$string = 'Newton, Einstein and Edison. end';  
echo preg_replace('/n/i', '<b>n</b>', $string); 

来自:newton、Einstein and爱迪生n。 end
至:Newton、Einsteinnd Ediso< b>n。 在这种情况下,

我希望替换所有 n 字母,除非它们是单词 end 的一部分,并且 Newton 不应更改为 牛顿

How do I:

  • replace characters in a word using preg_replace() but make
    an exception if they are part of a
    certain word.
  • replace an uppercase character with an
    uppercase replacement even if the
    replacement is lowercase and vice
    versa.

example:

$string = 'Newton, Einstein and Edison. end';  
echo preg_replace('/n/i', '<b>n</b>', $string); 

from: newton, Einstein and Edison. end
to: Newton, Einstein and Edison. end

In this case I want all the n letters to be replaced unless they are part of the word end And Newton should not change to newton

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

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

发布评论

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

评论(1

断桥再见 2024-10-01 10:31:04
echo preg_replace('/((?<!\be)n|n(?!d\b))/i', '<b>\1</b>', $string);

它匹配前面没有[单词边界 + e] 或后面没有 [d + 单词边界] 的任何字母“n”。

一般情况: /((?

echo preg_replace('/((?<!\be)n|n(?!d\b))/i', '<b>\1</b>', $string);

It matches any letter 'n' that is either not preceded by [word boundary + e] or not followed by [d + word boundary].

The general case: /((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文