|How to remove the last comma in a string?|
| 1:35 am on Mar 20, 2004 (gmt 0)|
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.
| 1:45 am on Mar 20, 2004 (gmt 0)|
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);
| 10:16 pm on Mar 21, 2004 (gmt 0)|
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
| 10:40 pm on Mar 21, 2004 (gmt 0)|
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