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.
To remove comma, you can replace. To replace, use str_replace() in PHP.
rtrim($my_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!
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!
$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, ",");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With