If Not True Then False

PHP: Remove Last Character from String – substr/substr_replace/rtrim - Comment Page: 1

This is a very common PHP question, how to remove last character from string in PHP? So here are three ways how to delete last character from string in PHP. Method 1 – PHP: Remove Last Character from String using substr and mb_substr substr and mb_substr commands usage substr($string, 0, -1); mb_substr($string, 0, -1); substr and mb_substr example: $string = "This is test...
Categories:
Tagged with:

12 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Input your comment.
help

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Input your name.

warlord

so what is the fastest and most efficient method of methods mentioned above?

reply Reply
Eduardo

Thanks! Very useful (: I was using “slice” from JS -> mystring.slice(0,-1) to remove last comma in a string result from php but now I know that with substr($mystring, 0, -1) I get the same result.

reply Reply
Pratik Upayay

Thanks for the a basic but a useful post. Was not sure about all 3 options.
Will follow few more posts from you.

reply Reply
David James Eddy

Decided to check the perf. of each of the above options, here’s the results using https://3v4l.org .

rtrim:
Version System time (s) User time (s) Memory (MiB)
hhvm 0.247 0.178 82.09
7.0 0.104 0.065 19.93
5.6 0.079 0.060 20.01
5.5 0.084 0.065 19.61
5.4 0.079 0.058 18.17
5.3 0.080 0.060 14.55

substr:
Version System time (s) User time (s) Memory (MiB)
hhvm 0.213 0.164 82.07
7.0 0.081 0.063 19.94
5.6 0.074 0.067 20.03
5.5 0.063 0.065 19.59
5.4 0.041 0.059 18.23
5.3 0.020 0.066 14.49

substr_replace:
Version System time (s) User time (s) Memory (MiB)
hhvm 0.107 0.199 81.87
7.0 0.025 0.066 19.94
5.6 0.021 0.061 20.00
5.5 0.022 0.056 19.59
5.4 0.023 0.058 18.23
5.3 0.021 0.061 14.56

Conclusion:
substr_replace is the overall; `best` option

reply Reply
nedir

the best way is rtrim(); function. because you can use clear “/” characters and the string can have a lot of “/” like “///” ;)

reply Reply
Marco Grazia

just for …
Obviously the method is among the slowest among those presented here, but using this method with rtrim (), you can remove an arbitrary character at the end of the string.

Actually I had thought originally to treat the string as an array, and try to delete the last character with array_pop ().
But apparently, even if you can handle the string as an array, ex .: $ text [0], $ text [1] … $ text [n-1].
When you try to put it into a function to PHP array tells you it’s not an array.
And make any string as an array with methods, such as with foreach () is longer a nightmare.

reply Reply