Jump to content

Simple Regex problem


robbyc

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/38022-simple-regex-problem/
Share on other sites

$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>

Link to comment
https://forums.phpfreaks.com/topic/38022-simple-regex-problem/#findComment-182468
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.