PHP Remove First and Last Character from String Example

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.

Recommended PHP Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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