开发者

PHP: replace characters and make exceptions (preg_replace)

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


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'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜