How to Remove Last Characters of a String in PHP?

Sovary July 16, 2023 241
1 minute read

Today PHP, I will show short tip how to remove last characters of string in PHP by using simple function. This guide will help you to delete last amount of characters of a text. For example we have a sentence and we want to remove last 5 characters of the sentence then we will use function in example below.

Basically, we may use built-in function substr() to remove character where you begin to remove character and the index where we want to end remove the text. Now we will use this function again to reversly remove string from backward. Let's have a look in the example below.

Using substr()

<?php
    
    $string = "Hello this is cambotutorial.com";

    $last2Char = substr($string, 0, -2);
    echo $last2Char."<br>";
        
    $last3Char = substr($string, 0, -3);
    echo $last3Char."<br>";
        
    $last4Char = substr($string, 0, -4);
    echo $last4Char."<br>";
        
    $last5Char = substr($string, 0, -5);
    echo $last5Char."<br>";
        
    $last7Char = substr($string, 0, -7);
    echo $last7Char."<br>";

Output:

Hello this is cambotutorial.c
Hello this is cambotutorial.
Hello this is cambotutorial
Hello this is cambotutoria
Hello this is cambotutor

This substr() accept 3 parameters. First is the string that we want to remove characters from, secondly is the index where to start. The last is reverse index character where we want to remove. Thanks for reading, please have a nice day!!.

You might also like...

PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him