Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove excess commas from string PHP

Tags:

php

I've filtered some keywords from a string, to remove invalid ones but now I have a lot of extra commas. How do I remove them so I go from this:

,,,,,apples,,,,,,oranges,pears,,kiwis,,

To this

apples,oranges,pears,kiwis

This question is unique because it also deals with commas at the start and end.

like image 815
Amy Neville Avatar asked Feb 03 '16 11:02

Amy Neville


People also ask

How to remove all comma from string in php?

To remove comma, you can replace. To replace, use str_replace() in PHP.

How to remove last comma from string in php?

rtrim($my_string, ',');

How do you remove the comma at the end of a string?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!

How to remove trailing comma in regex?

To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second. The method will return a copy of the string without the leading or trailing comma. Copied!


1 Answers

$string = preg_replace("/,+/", ",", $string);

basically, you use a regex looking for any bunch of commas and replace those with a single comma. it's really a very basic regular expression. you should learn about those!

https://regex101.com/ will help with that very much.

Oh, forgot: to remove commas in front or after, use

$string = trim($string, ",");
like image 50
Franz Gleichmann Avatar answered Oct 12 '22 16:10

Franz Gleichmann