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?
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
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.You can use substr:
echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'
This isolates the string from the start upto and including the second last character. In other words, it isolates the whole string except the last character.
In case the last character could be multi-byte, then mb_substr() should be used instead.
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.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.
Note that this function is not multibyte-safe, and will produce the undesired result if the last character will happen to be a multi-byte one.
substr_replace($str, $replacement, $start[, $length]) last couple of parameters limit the letters that are "surgically interventioned". I.e. substringing will only analyze/replace the substring's characters (in this case emptied). After this is done, the rest of the unaltered string is concatenated.You can use
substr(string $string, int $start, int[optional] $length=null);
See substr in the PHP documentation. It returns part of a string.
Use the regular expression end of string anchor "$"
$string = preg_replace("/,$/", '', $string);
"The fastest best code is the code that doesn't exist".
Speaking of edge cases, there is a quite common issue with the trailing comma that appears after the loop, when getting data from some stream
$str = '';
while ($row = getRow()) {
$str .= $row['value'] . ",";
}
which, I suppose, also could be the case in the initial question. In this case, the fastest method definitely would be not to add the trailing comma at all, using a flag for this
$str = '';
$first = true;
while ($row = getRow()) {
if ($first) {
$first = false;
} else {
$str .= ",";
}
$str .= $row['value'];
}
or, when we positively know that the first value cannot be empty, we can use the resulting string as such a flag
$str = '';
while ($row = getRow()) {
$str .= ($str !== '') ? "," : "";
$str .= $row['value'];
}
here we are checking whether $str has any value already, and if so - adding a comma before the next item, thus having no extra commas in the result.
There is more advance way for doing the same thing with pack() and unpack() binary functions as follows if somebody likes it:
$testStr = 'a,b,c,d,e,';
$arr = unpack('C*',$testStr);
unset($arr[strlen($testStr)]);
echo $output = pack('C*', ...$arr);
The unpack function is used to unpack binary data into an associative array. The C* format string in unpack is used to interpret the input string as an array of unsigned characters as specified in code. which returns array in below form.
Array ( [1] => 97 [2] => 44 [3] => 98 [4] => 44 [5] => 99 [6] => 44 [7] => 100 [8] => 44 [9] => 101 [10] => 44 )
Where 97 = "a" and 44 = "," which is ASCII value of character.
unpack('C*',$testStr);
C: Specifies that the data is a single byte (8 bits) and should be unpacked as an unsigned integer. *: Specifies that all bytes in the input string should be unpacked.
pack('C*', ...$arr);
The pack function on the other hand is used to pack data into a binary string. When used with the C* format string, pack takes an array of bytes (or integers representing bytes) and packs them into a binary string.
C: Specifies that the argument is an unsigned character (byte). *: Specifies that all elements of the array should be packed.
unset($arr[strlen($testStr)]);
The unset function here removes the last element from array. Which is ',' in this case.
Hope that helps.
if you do you really want to replace a last char:
$string = "a,b,c,d,e,";
$string[strlen($string)-1] = "";
echo $string; //output: a,b,c,d,e
Fatal error: Uncaught Error: Cannot assign an empty string to a string offset
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.