PHP Functions : Remove Last Character From String In PHP

PHP removes the last character from a string. This tutorial explains to you, how you can easily remove last character string form with example.

When you work with PHP, Many time, you want to you remove characters from strings. This tutorial shows you various PHP functions for removing the last character from the given string.

Remove Last Character From String In PHP | PHP Functions

This tutorial demonstrates an easy way for you. To remove the last character from string in PHP.

1. Method First – substr function

You can use the substr function of php for remove the last character from string in php.

Syntax:

The syntax of subster method is given below:

substr($string, 0, -1);

Example – Method First – substr function

 $string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . substr($string, 0, -1) . "\n"; 

Output

 Given string: Hello World!
 Updated string: Hello World

2. Method Second – substr_replace function

You can also use substr_replace for the remove the last character from string in php.

Syntax:

The basic syntax of substr_replace function is:

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

Example – substr_replace function

 $string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . substr_replace($string ,"",-1) . "\n";

Output

 Given string: Hello World!
 Updated string: Hello World 

3. Method Third – rtrim() function

You can use the PHP rtrim() function to remove the last character from the given string in PHP.

Syntax:

The basic syntax of rtrim() function is:

rtrim($string,'a');

Here “a” is the character that you want to remove in your string.

Example – rtrim() function

 $string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . rtrim($string, "!") . "\n";

Output

 Given string: Hello World!
 Updated string: Hello World  

Conclusion

PHP Remove the last character from a string. In this tutorial, you have many methods of PHP to remove the last character from any given strings.

3 replies to PHP Functions : Remove Last Character From String In PHP

  1. Helpful for substr_replace, substr or trim function to remove the last character from a string in PHP.

    Thanks tutsmake.com for remove last character from string in php.

  2. How to remove last 3 character from string php?

    • Using substr() function, You can remove 3 characters at the end of a string in PHP.
      like this :-
      echo substr($string, 0, -3);

Leave a Reply

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