Want to remove multiple commas [with or without spaces] with a single one. Tried this regex however it failed preg_replace("/s{1,5},s{1,5}+/", ", ", $string);
Tried other solutions but can’t find any solution where space also exists with comma.
Sample input
GUWAHATI, TEZPUR, , BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH ,
GUWAHATI, TEZPUR , , BAMUNI HILLS,, MAHABHAIRAB TEMPLE, AGNIGARH,
GUWAHATI, , TEZPUR, , BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH
Expected output
GUWAHATI, TEZPUR, BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH
2
Answers
You may use this solution:
RegEx Demo
Breakdown:
^[,h]+
: Match 1+ of comma or spaces after start|
: ORh*(,)(?:h*,)+h*
: Match 2 or more of comma optionally separated by spaces. Note that we match a single comma in capture group|
: OR[,h]+$
: Match 1+ of comma or spaces before end'$1 '
: Is replacement to put captured value of comma followed by a single spaceYou can
trim
the$string
from whitespace and commas usingtrim($string, ', nrtvx00')
(the chars are the defaulttrim
chars + a comma) and then usepreg_replace('/s*(?:,s*)+/', ', ', ...)
:See the PHP demo
The
s*(?:,s*)+
pattern matches zero or more whitespace followed with one or more sequences of a comma and zero or more whitespaces. Here is the regex demo.