Wrap string with other strings fluently in Laravel 9.x

Amit Merchant · March 31, 2022 ·

If you’ve ever been in a situation where you need to wrap your string with some characters, let’s say ", you most probably would do something like so.

$subject = '"'. $subject . '"';

As you can tell, you’ll need to concatenate the string with the characters that you want to wrap the string with.

Now, at first, this kind of looks viable but think about the scenario where you’re building a string using Laravel’s fluent method like so.

use Illuminate\Support\Str;

$input = 'hello world!';

$output = Str::of($input)
                ->replace('world', 'universe')

..And if you want to wrap this line with inverted commas (“), you can’t just do that fluently.

This is what the wrap helper method attempts to solve.

The wrap string helper

A recent PR added the wrap helper that would wrap the target string with the string given to it as a parameter. So, if you want to wrap a string with ", here’s how you can do it.

$input = 'hello world!';

$output = Str::of($input)
                ->replace('world', 'universe')

// outputs: "Hello universe!"

As you can tell, it’s fairly easy now to wrap string fluently without doing it manually.

You can even go further and change the string point and ending point of the wrapping like so.

$input = 'bar';

$output = Str::of($input)
                ->wrap('foo ', ' baz');

// outputs: "foo bar baz"
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!