Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...