Remove the Last character from a String in PHP

This article, will discuss multiple ways to remove the last character from a string in PHP.

Table Of Contents

Introduction

In PHP, strings are a sequence of characters, and there might be scenarios where you need to remove the last character from a string. This could be due to various reasons such as formatting, data cleanup, or preprocessing before storage or further processing. Let’s see how to do this.

Deleting Last character of String Using substr()

The substr() function in PHP is used to return a part of a string. We can use this function to get all the characters of the string except the last one. The syntax of the substr function is:

substr(string $string, int $start [, int $length ])

Here, $string is the original string, $start is the starting position, and $length is the length of the substring. To remove the last character, we set $start to 0 and $length to -1, which indicates all characters except the last one.

Let’s see the complete example,

<?php
$originalString = "This is a sample string";

// Remove the last character
$modifiedString = substr($originalString, 0, -1);

echo $modifiedString; // Outputs: This is a sample strin
?>

Output

This is a sample strin

In this code, $originalString is the string from which we want to remove the last character. We use substr to create $modifiedString, which is the original string minus its last character.

Summary

So, this way we can remove the last character from a String in PHP.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top