This article, will discuss multiple ways to remove the first and last character from a string in PHP.
Table Of Contents
Background
There are scenarios in PHP programming where you might need to modify a string by removing its first and last characters. For instance, consider the following string:
$originalString = "This is a sample string";
The objective is to remove the first (T) and the last (g) characters, resulting in:
"his is a sample strin"
Let’s examine some solutions to achieve this.
Solution 1: Using substr()
The substr() function in PHP can be used to return a part of a string. We can use it to get the substring excluding the first and last characters.
Let’s see the complete example,
Frequently Asked:
- Remove a backslash from a String in PHP
- Remove a string after a comma in PHP
- Remove all characters except numbers from a String in PHP
- Remove characters from String before a character in PHP
<?php $originalString = "This is a sample string"; // Remove the first and last characters $modifiedString = substr($originalString, 1, -1); echo $modifiedString; ?>
Output
his is a sample strin
In this code:
– substr($originalString, 1, -1) extracts a substring starting from the second character (index 1) of $originalString and excludes the last character.
– The resulting string has both the first and last characters removed.
Solution 2: Using mb_substr() for Multibyte Strings
If your string contains multibyte characters (like UTF-8), it’s safer to use mb_substr(), which is multibyte safe. This function is similar to substr() but is designed for strings with multibyte encodings.
Let’s see the complete example,
<?php $originalString = "This is a sample string"; // Remove the first and last characters for multibyte strings $modifiedString = mb_substr($originalString, 1, mb_strlen($originalString) - 2); echo $modifiedString; ?>
Output
his is a sample strin
In this code:
– We use mb_strlen($originalString) – 2 to calculate the length of the substring, excluding the first and last characters.
– mb_substr() then returns the substring, effectively removing the first and last characters.
Summary
Removing the first and last characters from a string in PHP can be achieved using either substr() for single-byte strings or mb_substr() for multibyte strings. Both functions allow you to specify the portion of the string you want to retain, making it easy to exclude specific characters from the beginning and end of the string.