Matthew Chambers
Matthew Chambers

Reputation: 877

Remove multiple commas regex

Can someone please let me know how I would remove multiple commas if they were next to one another in PHP.

$address= rtrim(preg_replace('!\s+!', ' ', $address_line_1.' '.$address_line_2.', '.$town_village_city.', '.$state_province_county.', '.$postal_code.', '.$country),',');
//return  preg_replace('/([!?,.])+/',' ',$address);
return  preg_replace('!\,+!',' ',$address);

For example I may have an address with no town_village so end up with multiple commas.

Also anyone good resources for testing PHP regex?

Upvotes: 0

Views: 4667

Answers (3)

mickmackusa
mickmackusa

Reputation: 48041

Perhaps it would be better if you pre-trim and pre-filter the values, then just implode to eliminate this XY Problem.

$parts = array_filter([
             trim(trim($address_line_1) . ' ' . $address_line_2),
             trim($town_village_city),
             trim($state_province_county),
             trim($postal_code),
             trim($country)
         ]);
return implode(', ', $parts);

Otherwise, you can use /,\K,+/ with an empty replacement string to only replace commas that occur immediately after a comma.

Or if dealing with comma-space sequences, you can use /, \K(?:, )+/.

Upvotes: 0

sebtucknott
sebtucknott

Reputation: 259

Probably a proper RegEx for this but here was my work around -

$cleanedAddress = str_replace(',',', ',preg_replace('/,+/', ',', $address));

Make $address just comma separated, run preg_replace to remove multiple commas, then use str_replace to turn commas to comma space!

Upvotes: 0

DesertEagle
DesertEagle

Reputation: 599

assuming there are no spaces between these commas, you can simply replace multiple commas with one comma:

$cleadAddress = preg_replace('/,+/', ',', $address);

although you are replacing every comma with a comma (!), you also replace multiple commas. It depends on your exact data if a more complex regex is worth the effort to save some execution time.

Upvotes: 4

Related Questions