Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Swapping multiple keywords in a string in Laravel

Update: After I published this article, I went ahead and raised this PR in the framework itself. So, starting v8.83.0 and Laravel 9, you’ll now be able to use it the following ways.

use Illuminate\Support\Str;

echo Str::swap([
    'PHP' => 'PHP 8',
    'awesome' => 'fantastic'
], 'PHP is awesome');

// PHP 8 is fantastic
 
$string = Str::of('Tacos are great!')
    ->swap([
        'Tacos' => 'Burritos',
        'great' => 'fantastic',
    ]);
 
// Burritos are fantastic!

Check out the documentation — Str::swap

If you’re still on versions earlier than 8.83.0, continue reading the article.


Sometimes, you might stumble upon a situation where you have some keywords and you want to replace those with certain keywords in the string.

Well, I just discovered a sleek Laravel macro by Aaron Francis that can do this with a convenient macro.

So, let’s say we have a string called “PHP is awesome” and we want to swap “PHP” with “PHP 8” and “awesome” with “fantastic” in this string.

Here’s how we can do using this macro.

use Illuminate\Support\Str;

Str::macro('swap', function($map, $string) {
    return str_replace(array_keys($map), array_values($map), $string);
});

$string = 'PHP is awesome';

echo Str::swap([
    'PHP' => 'PHP 8',
    'awesome' => 'fantastic'
], $string);

// PHP 8 is fantastic

You can swap multiple keywords in a string at a time just like that.

Very handy indeed!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?