How to Remove Space from String in Laravel?

15-Sep-2022

.

Admin

How to Remove Space from String in Laravel?

Hello Friends,

In this example, I will show you how to remove space from a string in laravel. step by step explain remove spaces from a string in output with laravel. if you want to see an example of how to strip all spaces out of a string in laravel then you are in the right place. let’s discuss about how to remove white space from the end of a string in laravel. you will do the following things for laravel remove spaces from the string code example.

The below example will only remove spaces. You can simply use the PHP str_replace() function to strip or remove all spaces inside a string. you can pass the PHP command to laravel controller and use that function.

You can use this example with laravel 6, laravel 7, laravel 8, and laravel 9 versions.

You have just to follow the below step and you will get the layout as below:

Step 1: Install Laravel


This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create RemoveSpaceController

we will create RemoveSpaceController with removeSpace() method to remove space from string. so you can see the below code with output:

php artisan make:controller RemoveSpaceController

App\Http\Controllers\RemoveSpaceController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RemoveSpaceController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$str = 'This is a simple piece of text.';

dd($this->removeSpace($str));

}

/**

* Display a listing of the resource.

*

* removeSpace function

*/

public function removeSpace($var)

{

return str_replace(' ', '', $var);

}

}

Step 3: Create Format Route

web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\RemoveSpaceController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('remove',[RemoveSpaceController::class,'index']);

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/remove

Output:

Thisisasimplepieceoftext.

It will help you...

#Laravel