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!
Like this article?
Buy me a coffee👋 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.