In this tutorial, You will learn how to remove the first and last characters from a string in PHP by using substr
, trim
and preg_replace
.
How to Remove First and Last Character from Strings in PHP?
Here are some methods:
- Method 1: Using substr() function
- Method 2: Using trim() function
- Method 3: Using preg_replace() function
Method 1: Using substr() function
To remove the first and last characters from a string, you can use substr() function twice – first to extract the substring without the first character, and then again to extract the substring without the last character.
Here is an example code snippet that demonstrates this method:
<?php
$str = "Hello World!";
$str = substr($str, 1, -1);
echo $str;
?>
Method 2: Using trim() function
To remove the first and last characters from a string using trim(), you can pass the characters to be removed as a second argument to the function.
Here is an example code snippet that demonstrates this method:
<?php
$str = "Hello World!";
$str = trim($str, "H!");
echo $str;
?>
Method 3: Using preg_replace() function
The preg_replace() function in PHP is used to perform regular expression-based search and replace operations on a string. you can use this function to remove the first and last characters from a string by using a regular expression pattern that matches the first and last characters and replacing them with an empty string.
Here is an example code snippet that demonstrates this method:
<?php
$str = "Hello World!";
$str = preg_replace('/^.|.$/', '', $str);
echo $str;
?>
Conclusion
In this tutorial, you explored substr(), trim(), and preg_replace() methods for removing the first and last characters from a string in PHP.