LLeoun Posted October 2, 2009 Share Posted October 2, 2009 Hi all, I need to replace one character when it does not come along with certain characters. Let me explain it with an example: I want to replace the letter o by the letter a when o is not followed by an r So the sentence: hello world Should be transformed into: hella world How can I do that?? Thanks once again Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted October 2, 2009 Share Posted October 2, 2009 $string = 'hello world'; $result = preg_replace('/o(?=[^r])/i','a',$string); echo $result; Quote Link to comment Share on other sites More sharing options...
thebadbad Posted October 2, 2009 Share Posted October 2, 2009 You can use a negative lookahead (?!regex), only matching when the regex fails to match: <?php $str = 'Hello world!'; echo preg_replace('~o(?!r)~i', 'a', $str); //Hella world! ?> Remove the i if the search shouldn't be case insensitive. Quote Link to comment Share on other sites More sharing options...
thebadbad Posted October 2, 2009 Share Posted October 2, 2009 $string = 'hello world'; $result = preg_replace('/o(?=[^r])/i','a',$string); echo $result; That won't replace an o at the last position in the string. Quote Link to comment Share on other sites More sharing options...
LLeoun Posted October 2, 2009 Author Share Posted October 2, 2009 Thanks a ton, worked great! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.