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($string, 0, -1);
mb_substr($string, 0, -1);

substr and mb_substr example:

$string = "This is test string..";
echo $string . "\n";
 
// substr function
echo "substr: " . substr($string, 0, -1);
 
echo "\n";
 
// mb_substr multibyte version
echo "mb_substr: " . mb_substr($string, 0, -1);
 
echo "\n";

Example output:

This is test string..
This is test string.
This is test string.

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

substr_replace command usage

substr_replace($string ,"",-1);

substr_replace example:

$string = "This is test string..";
echo $string . "\n";
 
// substr_replace function
echo "substr_replace: " . substr_replace($string ,"",-1);
 
echo "\n";

Example output:

This is test string..
This is test string.

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($string,'x');

rtrim example:

$string = "This is test string..";
echo $string . "\n";
 
// rtrim function
echo "rtrim: " . rtrim($string, ".");
 
echo "\n";

Example output:

This is test string..
This is test string
Follow If Not True Then False Updates!

6 Comments

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

  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.

  3. Thanks great work i was searching for it.

  4. Thanks, it helps me a lot.

  5. thanks it help me much

  6. thanks nice great job.

Leave a Comment

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

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=""> <strike> <strong>