Swapping multiple keywords in a string in Laravel

Amit Merchant · February 1, 2022 ·

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!')
        '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 (and 8.1), 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-read 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.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!