skip to Main Content

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


  1. 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
    Login or Signup to reply.
  2. You can trim the $string from whitespace and commas using trim($string, ', nrtvx00') (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, ", nrtvx00"));
    // => 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search