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

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners