tags:

views:

69

answers:

3

How can I remove extra commas and add commas for example using PHP

user submitted data

stack,,,,,,,,,,,,,,overflow

should output.

stack, overflow
+5  A: 
$out = preg_replace("/,+/",", ",$in);
mvds
@mvds - This function will add a space after all commas, even ones that already have a space after them.
Peter Ajtai
@Peter: the input condition was quite clear on that one: just commas. Replace the regexp with `"/,+\\s*/"` to also reduce whitespace to one space.
mvds
A: 

$str = preg_replace('/,+/' , ',' , $str);

This will replace each sequence of one or more commas with one comma.

Borealid
+1  A: 

preg_replace('/[,]+/', ',', $string); should do it... though depending on the nature of the input you may need a more complex expression.

prodigitalson