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 Link to comment https://forums.phpfreaks.com/topic/176276-replace-characters-when-not-followed-by-certain-characters/ 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; Link to comment https://forums.phpfreaks.com/topic/176276-replace-characters-when-not-followed-by-certain-characters/#findComment-929008 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. Link to comment https://forums.phpfreaks.com/topic/176276-replace-characters-when-not-followed-by-certain-characters/#findComment-929009 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. Link to comment https://forums.phpfreaks.com/topic/176276-replace-characters-when-not-followed-by-certain-characters/#findComment-929011 Share on other sites More sharing options...
LLeoun Posted October 2, 2009 Author Share Posted October 2, 2009 Thanks a ton, worked great! Link to comment https://forums.phpfreaks.com/topic/176276-replace-characters-when-not-followed-by-certain-characters/#findComment-929025 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.