www.friend0.in
www.friend0.in

Reputation: 257

Removing multiple commas with a single comma in PHP

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

Upvotes: 3

Views: 85

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627419

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.

Upvotes: 2

anubhava
anubhava

Reputation: 786041

You may use this solution:

$s = preg_replace('/^[,\h]+|\h*(,)(?:\h*,)+\h*|[,\h]+$/m', '$1 ', $s);

RegEx Demo

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

Upvotes: 3

Related Questions