Laravel 9 - Swapping Multiple Keywords in a String

Published on Jul 29, 2022

Hello Artisans, today we'll show how we can swap between multiple keywords. Sometimes we need to replace the keywords with some given keywords in a string. So, let's see how we can easily swap between multiple keywords in a string in our Laravel Application.

Note: Tested on Laravel 9.19.

Str::swap() method

Suppose we've a string and we want to replace some keywords in that string then how will you do it? No need to worry, for this type of situation Laravel comes with swap() method of Str class. Let's see the below code snippet.

use Illuminate\Support\Str;

            'shoutsdev' => 'shoutsdev',
            'awesome' => 'cool'
        ], 'shoutsdev is awesome'));

We can also achieve that result in a different way. Let's see below code snippet

dd(Str::of('Tacos are great!')
                'Tacos' => 'Burritos',
                'great' => 'fantastic',
        //it'll print Burritos are fantastic!

That's it for today. Hope you've enjoyed this tutorial. Thanks for reading. 🙂

Comments (0)