Laravel Replace Word Using str::replace() Example

Oct 12, 2022 . Admin



Hello Friends,

This example is focused on laravel replacing words using the str::replace() example. We will use how to use str::replace() in laravel. this example will help you Use str::replace() to replace words within a string in laravel. I would like to share with you how to replace words with str::replace() in laravel. Here, Creating a basic example of how to replace multiple words in a string with str::replace() 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', 'Mywebtuts.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 Mywebtuts.com
#Laravel