Laravel 10 Remove All Spaces from String Example

Hello Artisan, today I'll show you laravel remove all spaces from string. We will explore an example of removing all whitespace from a string in Laravel. I will demonstrate how to remove spaces from a string in Laravel. Let's delve into the detailed example.

We will utilize both str_replace() and preg_replace() functions in the Laravel project to eliminate all white spaces from the string. This example is applicable to Laravel versions 6, 7, 8, 9, and 10.

Table of Contents

  1. Example 1: using str_replace()
  2. Output
  3. Example 2: using preg_replace()
  4. Output

Example 1: using str_replace()

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public function index()
    {
        $string = "Hi, This is from Shouts.dev";

        $string = str_replace(' ', '', $string);

        dd($string);
    }
}

Output

"Hi,ThisisfromShouts.dev"

Example 2: using preg_replace()

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public function index()
    {
        $string = "Hi, This is from Shouts.dev";

        $string = preg_replace('/\s+/', '', $string);

        dd($string);
    }
}

Output

"Hi,ThisisfromShouts.dev"

That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚