kadin
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;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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")
[ ] = 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.
ASKER
Thanks to both of you for your help.
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
ASKER
Thanks for the comment ozo.
gr8gonzo, after more testing, your suggestion seems to work really well.
gr8gonzo, after more testing, your suggestion seems to work really well.
$tagsString = ' aaa, , , bbb, ccc';
$tags = preg_replace('/\s?,[,\s]+/
echo $tagsString = " aaa, , , bbb, ccc\n"; //original
echo $tags;