How to remove the last character of a string

Remove the last character in PHP

In Perl, the chop function removes the last character in a string, but in PHP it removes trailing white spaces only. To get the same functionality into PHP you can use the substr_replace() function. For example:

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

will remove the last character of $string. You can play with it and replace the last character with empty space if you need such a functionality in your script.

Remove the last character in BASH

Since most of the visits on this page had the ‘Remove last character bash’ search engine keyword, I figured that people might need that section as well, so here it is. To remove the last character from a string/file using bash scripting you need to use the echo option and ‘pipe’ it to the variable itself. For example:

var=”My String with an additional a at the end. a”
var=$(echo ${var%a})

Now, if you do echo $var you will see that it will display “My String with an additional a at the end.” without the additional a at the end :)

Bookmark and Share

  • No Related Post
bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark
tabs-top  banner ad


5 Responses to “How to remove the last character of a string”

  1. People would rather expect to have something that can apply to any last character. Whether it is an a or any other letter.

    This code will do it

    x=JohnDoee;
    echo $x
    x=$(echo $x | rev); x=$(echo ${x:1} | rev);
    echo $x

    Enjoy

  2. alan says:

    On a file you could just run:

    sed -n ’s/.$//p’ filename.txt

    to print each line in the file without the last character. I don’t see much usage in it though :)

  3. flash gamer says:

    thanks works great

  4. Stephen Pickett says:

    I needed to remove the first character, so I adapted Alan’s code (by the way, thanks Alan!):

    x=JJohnDoe;
    echo $x
    x=$(echo ${x:1});
    echo $x

  5. Sam says:

    I need to remove several characters from the end of a line, how do I do it? For example, let’s remove two letters from JJohnDoe and leaving JJohnD. Any suggestions?

Leave a Reply