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
2010-08-09 16:03:22
+1
A:
You don't need regex for this.
$output = explode(',', $input);
$output = array_map('trim', $output);
$output = implode(',', $output);
Hammerite
2010-08-09 16:12:35
True, but regex (especially a trivial one like this) should be significantly more efficient than mapping functions and multiple data type conversions...
ircmaxell
2010-08-09 16:24:52
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
2010-08-09 16:46:05
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
2010-08-09 16:46:41
@ircmaxell ~30% faster on my machine for ~1000 character text blobs littered with commas
meagar
2010-08-09 16:49:21
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
2010-08-09 17:09:51