Quantcast
Channel: How to remove unwanted commas from a string? - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by Matteo Tassinari for How to remove unwanted commas from a string?

$
0
0

Try this:

$str = preg_replace('/,{2,}/', ',', trim($str, ','));

The trim will remove starting and trailing commas, while the preg_replace will remove duplicate ones.

See it in action!

Also, as @Spudley suggested, the regex /,{2,}/ could be replaced with /,,+/ and it would work too.

EDIT:

If there are spaces between commas, you may try adding the following line after the one above:

$str = implode(',', array_map('trim', explode(',', $str)))

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>