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 usingsquish
would make the content appear more professional.
And that’s all about the new squish
helper method!
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.