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?
Join Stack Overflow to learn, share knowledge, and build your career.
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?
First, I try without a space, rtrim($arraynama, ",");
and get an error result.
Then I add a space and get a good result:
$newarraynama = rtrim($arraynama, ", ");
$string
by your data, and echo the whole thing: echo rtrim("a,b,c,d,e,", ",");
– anon
Apr 8 '11 at 9:18
A;B;C;D;
to A;B;C;D
, but will also transform A;B;;;
to A;B
. Often one wants to preserve the delimiters between empty values, because a CSV parser could need to determine the number of fields from the string itself.
– etuardu
Jan 13 '15 at 19:51
You can use substr
:
echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'
trim
and rtrim
do not remove the last character in a string. Although sometimes that is all they do, they will often remove many characters from the string. e.g. rtrim('Assess','s')
gives you 'Asse', not 'Asses'. That's why this answer is better than the accepted answer.
– Buttle Butkus
Mar 20 '15 at 4:52
An alternative to substr
is the following, as a function:
substr_replace($string, "", -1)
Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.
substr_replace($str, $replacement, $start[, $length])
last couple of parameters limit the letters that are "surgically interventioned". I.e. substr
inging will only analyze/replace the substring's characters (in this case emptied). After this is done, the rest of the unaltered string is concatenated.
– CPHPython
Aug 9 '18 at 10:03
You can use
substr(string $string, int $start, int[optional] $length=null);
See substr in the PHP documentation. It returns part of a string.
trim()
. So he means "How to remove last specific characters from string?" and not "the last". All other answers are "wrong" by that. The only wrong duplicate marking has this question. – mgutt Apr 2 '15 at 9:53