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 depth.
Here, I’ll show you how to eliminate every space from a string in a Laravel project using only two methods. Laravel’s str_replace() and preg_replace() methods 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, abhishek singh";
$string = str_replace(' ', '', $string);
dd($string);
}
}
Output:
Hi,abhisheksingh
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, abhishek singh";
$string = preg_replace('/\s+/', '', $string);
dd($string);
}
}
Output:
Hi,abhisheksingh
[…] Example: Laravel Remove All Spaces from String […]