Link to home
Start Free TrialLog in
Avatar of kadin
kadinFlag for United States of America

asked on

Regex. Replace all occurences of , , . That's (comma, one or more spaces, comma)

My code can replace the first occurrence of (comma, one or more spaces, comma) with just one comma. But I'm still left with one more comma, space, comma. I want to remove all occurrences of the unneeded commas and the empty spaces between them. Does someone have a suggestion? Thanks.

 $tagsString = ' aaa,      , , bbb, ccc';

 $pattern = '/(,\s+,)+/'; 
 $tags = preg_replace($pattern, ',',$tagsString);

 echo $tagsString = ' aaa,      , , bbb, ccc<br>'; //original
 echo $tags;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try this:
$tagsString = ' aaa,      , , bbb, ccc';
$tags = preg_replace('/\s?,[,\s]+/', ',',$tagsString);
echo $tagsString = " aaa,      , , bbb, ccc\n"; //original
echo $tags;
Avatar of kadin

ASKER

Wow. Thanks. That's simpler than I expected. I wish I could understand it.
\s = Any single character of white space
[  ] = Any single character matching a character inside the braces. For example [ab] would match "a" or "b"
+ = Match at least one or more of the preceeding character. For example, [ab]+ would match 1 or more instances of a or b (like "a" or "aaabbaab")
Um, I thought you wanted to remove the spaces around the commas, too? The answer you accepted leaves the spaces in there.
Avatar of kadin

ASKER

Thanks to both of you for your help.
Avatar of kadin

ASKER

No. I have another part of the code that does that. I just wanted any empty tags to be deleted. Thanks again.
/\s?,[,\s]+/ matches commas without one or more spaces, or spaces after only a single comma
Avatar of kadin

ASKER

Thanks for the comment ozo.

gr8gonzo, after more testing, your suggestion seems to work really well.