[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 493
  • Last Modified:

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

0
kadin
Asked:
kadin
  • 4
  • 3
  • 2
1 Solution
 
ozoCommented:
$pattern = '/(,\s+)+,/';
0
 
gr8gonzoConsultantCommented:
Try this:
$tagsString = ' aaa,      , , bbb, ccc';
$tags = preg_replace('/\s?,[,\s]+/', ',',$tagsString);
echo $tagsString = " aaa,      , , bbb, ccc\n"; //original
echo $tags;
0
 
kadinAuthor Commented:
Wow. Thanks. That's simpler than I expected. I wish I could understand it.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
gr8gonzoConsultantCommented:
\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")
0
 
gr8gonzoConsultantCommented:
Um, I thought you wanted to remove the spaces around the commas, too? The answer you accepted leaves the spaces in there.
0
 
kadinAuthor Commented:
Thanks to both of you for your help.
0
 
kadinAuthor Commented:
No. I have another part of the code that does that. I just wanted any empty tags to be deleted. Thanks again.
0
 
ozoCommented:
/\s?,[,\s]+/ matches commas without one or more spaces, or spaces after only a single comma
0
 
kadinAuthor Commented:
Thanks for the comment ozo.

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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now