Welcome to WebmasterWorld Guest from 23.22.220.37

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

How to remove the last comma in a string?

     
1:35 am on Mar 20, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 2, 2002
posts:1099
votes: 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.

Thanks!

1:45 am on Mar 20, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 22, 2002
posts:2546
votes: 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)

New User

10+ Year Member

joined:Mar 9, 2004
posts:5
votes: 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)

Moderator

WebmasterWorld Administrator ergophobe is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Apr 25, 2002
posts:8127
votes: 88


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

Tom

 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members