Laravel: Remove All Spaces from a String with Examples
Today, We will learn Laravel: Remove All Spaces from a String with Examples. In this tutorial, I will give you Laravel: Remove All Spaces from a String with Examples. Learn how to efficiently remove all spaces from a string in Laravel using built-in PHP functions and helper methods. This guide provides clear examples and practical tips to handle strings in your Laravel projects.
Here, I will show you two simple ways to remove all spaces from a string in a Laravel project. We will use the str_replace() and preg_replace() functions to eliminate all whitespace from strings. This example is compatible with Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10 versions.
Laravel: Remove All Spaces from a String with Examples
1. using str_replace()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$string = "Hi, This is a Laravel example";
// Remove all spaces from the string
$string = str_replace(' ', '', $string);
// Output the modified string
dd($string); // Output: "Hi,ThisisaLaravelexample"
}
}
Explanation:
- Input String: “Hi, This is a Laravel example“.
- str_replace() Function: Replaces all spaces (‘ ‘) in the string with an empty string (”).
- Output: The string is displayed without any spaces using dd().
2. using preg_replace()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$string = "Hi, This is a Laravel example";
// Remove all spaces from the string using preg_replace
$string = preg_replace('/\s+/', '', $string);
// Output the modified string
dd($string); // Output: "Hi,ThisisaLaravelexample"
}
}
Explanation:
- Input String: “Hi, This is a Laravel example“.
- preg_replace() Function:
- /\s+/: Matches any whitespace characters (spaces, tabs, newlines).
- ”: Replaces the matched whitespace with an empty string.
- Output: The modified string with all spaces removed is displayed using dd().