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

I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.
[…] Example: Laravel Remove All Spaces from String […]