phpcsvdelimitertruncatetrailing

Remove trailing delimiting character from a delimited string


What is fastest way to remove the last character from a string?

I have a string like

a,b,c,d,e,

I would like to remove the last ',' and get the remaining string back:

OUTPUT: a,b,c,d,e

What is the fastest way to do this?


Solution

  • Contrary to the question asked, rtrim() will remove any number of characters, listed in the second argument, from the end of the string. In case you expect just a single comma, the following code would do:

    $newarraynama = rtrim($arraynama, ",");
    

    But in my case I had 2 characters, a comma and a space, so I had to change to

    $newarraynama = rtrim($arraynama, " ,");
    

    and now it would remove all commas and spaces from the end of the string, returning a, b, c, d, e either from a, b, c, d, e,, a, b, c, d, e,,,, a, b, c, d, e, or a, b, c, d, e , ,, , ,

    But in case there could be multiple commas but you need to remove only the last one, then rtrim() shouldn't be used at all - see other answers for the solution that directly answers the question.

    However, rtrim() could be a good choice if you don't know whether the extra character could be present or not. Unlike substr-based solutions it will return a, b, c, d, e from a, b, c, d, e