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 https://twitter.com/aarondfrancis/status/1488298201937588229 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.

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([ 'awesome' => 'fantastic' ], $string); // PHP 8 is fantastic You can swap multiple keywords in a string at a time just like that.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners