homepage Welcome to WebmasterWorld Guest from 54.167.174.90
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
How to remove the last comma in a string?
irock

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3238 posted 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.

Thanks!

 

Birdman

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3238 posted 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);

Moonface

10+ Year Member



 
Msg#: 3238 posted 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

ergophobe

WebmasterWorld Administrator ergophobe us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 3238 posted 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

Tom

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved