myares Posted October 16, 2010 Share Posted October 16, 2010 I wanted to sort out a code which will work like this (for any variable): $x = "A.S.M. Jackel" $x = "A. S. M. Jackel" I mean it will check the variable and if the variable doesn't have a space next to the . [dot] it will replace it and add a space next to it. If it already have a space next to the . [dot] it won't change anything. Can someone help me out? Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/ Share on other sites More sharing options...
gizmola Posted October 16, 2010 Share Posted October 16, 2010 preg_replace is what you want to look at. Check this out: $x = "A.S.M. Jackel"; $y = "A. S. M. Jackel"; $pattern = '/(\.)([^ ])/'; $replace = '$1 $2'; echo preg_replace($pattern, $replace, $x); echo ' '; echo preg_replace($pattern, $replace, $y); Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/#findComment-1122675 Share on other sites More sharing options...
myares Posted October 16, 2010 Author Share Posted October 16, 2010 thanks a lot buddy! it worked! Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/#findComment-1122681 Share on other sites More sharing options...
salathe Posted October 16, 2010 Share Posted October 16, 2010 For what it's worth, life could be made simpler by using a regular expression which reads like match a dot which is not followed by a space character: $pattern = '/\.(?! )/'; $replace = '. '; The (?! ) is a "negative lookahead assertion" and is a fancy way of saying, "take a peek at the next character and make sure it is not a space". See http://php.net/regexp.reference.assertions Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/#findComment-1122773 Share on other sites More sharing options...
gizmola Posted October 17, 2010 Share Posted October 17, 2010 Yeah Salathe has a better solution in this case even though they both work ok. Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/#findComment-1122871 Share on other sites More sharing options...
sasa Posted October 18, 2010 Share Posted October 18, 2010 or $pattern = '/\. */'; $replace = '. '; Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/#findComment-1123317 Share on other sites More sharing options...
salathe Posted October 18, 2010 Share Posted October 18, 2010 or $pattern = '/\. */'; $replace = '. '; Sure, except that doesn't do what the OP asked for. Quote Link to comment https://forums.phpfreaks.com/topic/215995-regular-expression-help/#findComment-1123321 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.