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
CodePudding user response:
You may use this solution:
$s = preg_replace('/^[,\h] |\h*(,)(?:\h*,) \h*|[,\h] $/m', '$1 ', $s);
Breakdown:
^[,\h]
: Match 1 of comma or spaces after start|
: OR\h*(,)(?:\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 space
CodePudding user response:
You can trim
the $string
from whitespace and commas using trim($string, ', \n\r\t\v\x00')
(the chars are the default trim
chars a comma) and then use preg_replace('/\s*(?:,\s*) /', ', ', ...)
:
<?php
$string = ", , GUWAHATI, TEZPUR, , BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH , ";
echo preg_replace('/\s*(?:,\s*) /', ', ', trim($string, ", \n\r\t\v\x00"));
// => GUWAHATI, TEZPUR, BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH
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.