tags:

views:

93

answers:

3

I have a string like following:

test1, test2, test3, test4,

When I use the implode function on this I get back that there are 5 elements in the array.

How can i not take into account the last extra comma ?

or better yet, how can i substring that so that there is no extra comma in the end.

+5  A: 

You can remove trailing commas (or any character) using rtrim();
Try this:
$str = rtrim('test1, test2, test3, test4,', ',');

See the doc for rtrim() @ http://us2.php.net/manual/en/function.rtrim.php

Arms
or even use trim() to remove the one in front, if there is any.
thephpdeveloper
A: 

Maybe the rtrim() is better, as Arms suggested. But as you've asked for substring, just to have it registered...

substr($string, 0, -1);

When the secound parameter is a negative value, it is going to act like strlen($string)-N and get you the string missing the last N characters.

Havenard
A: 

I would probably use

preg_split('#, *#', $str, null, PREG_SPLIT_NO_EMPTY)

which would be even more flexible with the input (handles consecutive commas, lack of space or doubled space, etc...) Of course, it depends on how confident you are the input will remain the same.

See preg_split()'s manual entry.

Josh Davis
People downvoting valid answers? Interesting.
Josh Davis