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') ->camel();
..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.
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') ->ucfirst() ->wrap('"'); // 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"
👋 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!