Forum Moderators: coopster

Message Too Old, No Replies

How to remove the last comma in a string

         

phpwillie

5:41 am on Sep 16, 2011 (gmt 0)

10+ Year Member



There was an old post on this topic, and the question went something like below:

"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."

A few suggestions were using eregi_replace() or substr(). Even though substr() suggestion was pretty clever (see below), it is simply chopping out the last character regardless it is a comma or not. And eregi_replace function has been deprecated as of PHP 5.3.0. My suggestion is to use preg_replace() instead.

For comparison purposes, I listed both substr() and preg_replace() example below. Enjoy and please comment/suggest new ways if you wish.

$str = "A product, B product, C product, D product, E product,";
$str = substr($str, 0, -1); //this will removed the last char in $str

-OR-

$mystr = "A product, B product, C product, D product, E product,";

//do this optionally for just in case any space or \n was added at the end
$mystr = trim($mystr);

$mystr = preg_replace('/,$/','',$mystr);

That is it!

lostdreamer

8:02 am on Sep 16, 2011 (gmt 0)

10+ Year Member



$mystr = rtrim($mystr, ",");

This will trim the comma's from the right side of the string....

rocknbil

4:14 pm on Sep 16, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A few suggestions were using eregi_replace() or substr()


ereg... functions are deprecated. Use preg... functions. one scenario where rtrim won't work is if there are spaces - or maybe there are only spaces on some of them - then preg_replace() will be handy.

$line = preg_replace('/,\s*$/','',$line);

\s* = zero or more white space characters ([space], \n, \r,\t)
$ = absolute line end.

phpwillie

4:02 am on Sep 18, 2011 (gmt 0)

10+ Year Member



Yep, I've already said eregi_replace function was deprecated. And your solution with preg_replace is even better than mine! Thanks rocknbil.