|How to remove the last comma in a string?|
Hi, I got a feed in which one of the 'childs' look like this
A product, B product, C product, D product, E product,
I was wondering how to remove the last comma.
You could use substr() [php.net] to strip the last character off the string.
$str = "A product, B product, C product, D product, E product,";
$str = substr($str, 0, strlen($str)-1);
or use eregi_replace
$string=eregi_replace(',$', '', $string);
the $ means from the end of the string, so..
replace the comma from the end of string with an empty space
Birdman's solution is better than a regex solution, since the regex engine takes more time and processing. Usually best to avoid if another built-in function does it.
However, Birdman's solution is unnecessarily complicated. You don't need to know the string length. Just do this
$str = substr($str, 0, -1);
That will cut the last char off a string. From the manual:
If length is given and is negative, then that many characters will be omitted from the end of string