Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new squish() helper in Laravel 9.x

April 12, 2022 ·

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);

// 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);

// 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')

// outputs: hello universe!


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 (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!