tags:

views:

99

answers:

3

I'm looking for regular expressions to remove space and whitespace before and after a comma.

+6  A: 

Try this:

$output = preg_replace('/\s*,\s*/', ',', $str);

This will replace all commas with possible leading and trailing whitespace characters (\s) by a single comma.

Gumbo
+3  A: 
preg_replace('/\s*,\s*/', ',', $target_string);
theraccoonbear
+1  A: 

You don't need regex for this.

$output = explode(',', $input);
$output = array_map('trim', $output);
$output = implode(',', $output);
Hammerite
True, but regex (especially a trivial one like this) should be significantly more efficient than mapping functions and multiple data type conversions...
ircmaxell
This is going to trim new lines from before/after commas in addition to the whitespace. If that's acceptable, it's definitely the fastest option.
meagar
I guess it's really a question of which you find more readable. I find what I've posted to be easier to comprehend than a regex, but that's because I don't deal with regexes a lot. I can see how someone might find the regex approach easier to understand at a glance, and that counts for a lot.
Hammerite
@ircmaxell ~30% faster on my machine for ~1000 character text blobs littered with commas
meagar
This is also going to remove spaces/newlines from the outer edges of the text. Ex. " Some text , other text. " would become "Some text,other text."
Inigoesdr