robbyc Posted February 11, 2007 Share Posted February 11, 2007 Ok this will probably seem like a simple question but I am quite new to regular expressions. I have strings that may look like the following: , , , word1 , word2 , , word3 word4 , word5 word6 word7 , , word8 , Which I want to be converted to this: word1,word2,word3 word4,word5 word6 word7,word8 I currently do the following //remove any start and end spaces $string = trim($string); //ensure there are no multiple spaces $string = preg_replace('/\s\s+/', '\s' , $string); //replace any spaces followed by a comma with a single , $string = preg_replace('/\s,/', ',', $string); //replace any commas followed by a space with a single , $string = preg_replace('/,\s/', ',', $string); //replace any multiple commas with a single , $string = preg_replace('/,+/', ',', $string); if(substr($string, 0, 1) == ',') { $string = substr($string, 1); } if(substr($string, -1, 1) == ',') { $string = substr($string, 0, strlen($string)-1); } I am sure there is a more efficient way to achieve this, any suggestions? Thanks Quote Link to comment Share on other sites More sharing options...
effigy Posted February 12, 2007 Share Posted February 12, 2007 $string = preg_replace('/\s\s+/', '\s' , $string); ...will not work because \s is literal in the replacement. Also, you don't need the extra \s when you've used a +, which already specifies one or more. This code can be changed to: $string = preg_replace('/\s+/', ' ' , $string); However, this is a bad idea in case the data uses spaces. $string = preg_replace('/\s,/', ',', $string); //replace any commas followed by a space with a single , $string = preg_replace('/,\s/', ',', $string); ...can be done in one step with \s*,\s*, and should also serve as a replacement for the "fix multiple whitespace" code above. if(substr($string, 0, 1) == ',') { $string = substr($string, 1); } if(substr($string, -1, 1) == ',') { $string = substr($string, 0, strlen($string)-1); } ...can be handled with /^,|,\z/. Resulting in: <pre> <?php $string = ', , , word1 , word2 , , word3 word4 , word5 word6 word7 , , word8 ,'; //remove any start and end spaces. $string = trim($string); //remove space around commas. $string = preg_replace('/\s*,\s*/', ',', $string); //replace multiple commas with a single comma. $string = preg_replace('/,+/', ',', $string); //remove commas from the ends. $string = preg_replace('/^,|,\z/', '', $string); echo $string; ?> </pre> 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.