views:

57

answers:

1

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

+1  A: 
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'

konforce
I would do the look-behind after matching the letter: `/$LETTER(?<!\b$PREFIX$LETTER)(?!$SUFFIX\b)/i`
Gumbo
@Konforce. This is the second time you make my day. Big big thank you!!
dany
@Gumbo, Thank you very much for the reply!
dany