I’d like to demonstrate how to remove every space from a string using Laravel today. We’ll look at a Laravel example that eliminates all whitespace from a string. I’ll demonstrate how to eliminate spaces from strings in Laravel. We’ll utilise the Laravel method for removing spaces from strings. So, let’s examine an example in more detail.
Here, I’ll show you how to eliminate every space from a string in a Laravel project using just two methods. Laravel’s str_replace() and preg_replace() functions will be used to eliminate all whitespace from strings.
This example works with versions of Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10.
Example 1: using str_replace()
<?php
namespace App\Http\Controllers;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$string = "Hi, This is abhishek";
$string = str_replace(' ', '', $string);
dd($string);
}
}
// Output:
HiThisisabhishek
Example 2: using preg_replace()
<?php
namespace App\Http\Controllers;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$string = "Hi, This is from ItSolutionStuff.com";
$string = preg_replace('/\s+/', '', $string);
dd($string);
}
}
// Output:
HiThisisabhishek