PHP: Remove Last Character from String – substr/substr_replace/rtrim

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 and mb_substr example:

Example output:

Method 2 – PHP: Remove Last Character from String using substr_replace

substr_replace command usage

substr_replace example:

Example output:

Method 3 – PHP: Remove Last Character from String using rtrim

Note: rtrim function is not working exactly same way as substr and substr_replace, but it is of course useful some cases. Rtrim function trims all specified characters from end of the string.

rtrim command usage

rtrim example:

Example output:

Share this post

10 Comments

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

    Reply
  2. 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
  3. Thanks great work i was searching for it.

    Reply
  4. thanks it help me much

    Reply
  5. thanks nice great job.

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

    Reply
  7. 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
  8. the best way is rtrim(); function. because you can use clear “/” characters and the string can have a lot of “/” like “///” ;)

    Reply
  9. very very good
    thanks .

    Reply

Submit a Comment

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