Laravel 10 - How to Remove First and Last Character

Hello Artisan, today I'll show you how to remove first and last character from an string. Sometimes we ran into a situation where we need to remove some specific string from sentence or word. I'll show you two examples for that. So, let's see how we can easily remove a character from the string.  

Note: Tested on Laravel 10.0

Table of Contents

  1. Example 1
  2. Example 2

Example 1

using substr()

I'll show two example but I preferred this one most. Because in real life, I found it very useful and it's easy to useful too. Let's see the below code snippet.

$str = "Hello World!";
$str = substr($str, 1, -1);

which'll generate the below output

Example 2

using preg_replace()

In the 2nd example we'll use preg_replace() to achieve our expected result. Let's see the below code snippet.  

$str = "Hello World!";
$str = preg_replace('/^.|.$/', '', $str);

which'll generate the same output as step1

That's it for today. I hope this tutorial will helpful with the real life application. Thanks for reading. ๐Ÿ™‚