How to Remove the Last Character from a String in PHP
In this post, I will share the best way to remove the last character from a string in PHP, you can use one of the following methods. All the methods mentioned belows are tried and tested with latest PHP 8.x version.
Method 1: Using substr()
The substr() function allows you to extract a part of a string. To remove the last character, specify the start and length of the substring you want to keep.
<?php
$string = "Hello, World!";
$result = substr($string, 0, -1); // Removes the last character
echo $result; // Output: Hello, World
?>
Method 2: Using rtrim()
If the last character is whitespace or a specific character, you can use rtrim().
<?php
$string = "Hello, World!";
$result = rtrim($string, "!"); // Removes the "!" at the end
echo $result; // Output: Hello, World
?>
Method 3: Using preg_replace()
For pattern-based removal, preg_replace() can be used.
<?php
$string = "Hello, World!";
$result = preg_replace('/.$/', '', $string); // Removes the last character
echo $result; // Output: Hello, World
?>
Let me know if you have any questions in the comment section below! 😊