Search code examples
phppreg-replaceuppercaselowercase

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


Solution

  • 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'