Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Wrap string with other strings fluently in Laravel 9.x

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 (including 8.1, 8.2, and 8.3), 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-digest 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.

Like this article? Consider leaving a


👋 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.