How to Replace String in Laravel?

12-Oct-2022

.

Admin

How to Replace String in Laravel?

Hello Friends,

In this tutorial, we will go over the demonstration of how to replace a string in laravel. if you have a question about removing and replacing string laravel code example then I will give a simple example with a solution. I would like to share with you the laravel string to replace all code examples. I explained simply step by step how to replace multiple words in a string in laravel.

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

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 ReplaceStringController

we will create ReplaceStringController with Str::replace() method to replace string. so you can see the below code with output:

php artisan make:controller ReplaceStringController

App\Http\Controllers\ReplaceStringController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Str;

class ReplaceStringController extends Controller

{

public function replaceString()

{

$string = 'Welcom to Laravel';

$replaced = Str::replace('Laravel', 'NiceSnippets.com', $string);

dd($replaced);

}

}

Step 3: Create Format Route

web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ReplaceStringController;

/*

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

| 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('/replace', [ReplaceStringController::class, 'replaceString']);

Step 4: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/replace

Output:

Welcome to NiceSnippets.com

#Laravel