Remove the last N characters from a String in PHP

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

Table Of Contents

Background

In PHP, you may encounter scenarios where you need to modify a string by removing a certain number of characters from its end. This is a common requirement in string manipulation, such as formatting output, cleaning data, or preparing strings for further processing.

For example, if we have the following string:

$originalString = "This is a sample string";

And we want to remove the last 3 characters, the desired output should be:

"This is a sample str"

Now, let’s look at different methods to achieve this in PHP.

Solution 1: Using substr()

The substr() function in PHP is used to return a part of a string. To remove the last N characters, we can use this function to get the substring starting from the first character up to the length of the string minus N.

Let’s see the complete example,

<?php
$originalString = "This is a sample string";
$n = 3; // Number of characters to remove

// Remove the last N characters
$modifiedString = substr($originalString, 0, -$n);

echo $modifiedString;
?>

Output

This is a sample str

In this code:
– $n is the number of characters we want to remove.
– substr($originalString, 0, -$n) returns a substring starting from the beginning of $originalString and excludes the last N characters.
– We print the modified string which has the last 3 characters removed.

Solution 2: Using mb_substr() for Multibyte Strings

If you’re dealing with multibyte character encodings like UTF-8, it’s safer to use mb_substr() which is multibyte safe. This function works similarly to substr() but is more suitable for strings containing characters in various encodings.

Let’s see the complete example,

<?php
$originalString = "This is a sample string";
$n = 3; // Number of characters to remove

// Remove the last N characters for multibyte strings
$modifiedString = mb_substr($originalString, 0, mb_strlen($originalString) - $n);

echo $modifiedString;
?>

Output

This is a sample str

In this code:
– We use mb_strlen($originalString) – $n to calculate the length of the substring we want to keep.
– mb_substr() then returns the substring up to the calculated length, effectively removing the last N characters.

Summary

In PHP, removing the last N characters from a string can be achieved using either substr() for single-byte strings or mb_substr() for multibyte strings. These functions provide a straightforward way to manipulate string lengths according to your needs.

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