Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new squish() helper in Laravel 9.x

Oftentimes, we need to trim the user-entered input to remove the additional white spaces around the string.

The defacto method we could use to accomplish this in PHP is the trim() method which can strip whitespace (or other characters) from the beginning and end of a string like so.

$text   = "\t\tHello world!   ";
$trimmed = trim($text);

var_dump($trimmed);
// outputs: Hello world!

As you can tell, the trim() method can easily remove the white space around the string but there could be a scenario where you may want to remove additional whitespaces which are there in between the strings.

To mitigate this, we now have a new helper method called squish() in Laravel 9.x.

The squish() helper - Trim on steriods

This PR by Dwight Watson introduces this squish() helper method in Laravel 9.x which is not only can remove the whitespaces from the beginning and ending of a string but also removes unnecessary whitespaces in between of the string.

Check the example below.

use Illuminate\Support\Str;

$text = ' PHP    is  awesome  ';
$squished = Str::squish($text);

var_dump($squished);
// outputs: PHP is awesome

As you can tell, the squish() helper trims the whitespaces around the string as well as removes unwanted spaces from in between the string intelligently, leaving a nice trimmed down string!

This also works fluently like so.

use Illuminate\Support\Str;

$input = '  hello     world! ';

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

var_dump($output);
// outputs: hello universe!

Usecases

Quoting the author from the PR, here are some of the use-cases for this helper method.

My use-cases are both when outputting user input that had additional unnecessary whitespace, and also when creating interpolated strings that have optional values (i.e. "A {$description} listing has been created."). In both of these instances using squish would make the content appear more professional.

And that’s all about the new squish helper method!

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?

Buy me a coffee

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

Comments?