Laravel 9 - The squish() helper method

Hello Artisans, today I'll talk about one of the handy method called squish() helper. Most of the times we need to remove the whitespaces from the user inputted text.

Note: Tested on Laravel 9.19.

squish() helper method

Of course we can use the PHP's by default method called trim(). But it'll only remove the whitespace from the beginning and ending of a string like below.

<?php
$text = "\t\tHello world   ";
$trimmed = trim($text);

// it'll print "Hello world"

So, we can easily remove the whitespace around the string. But may be there is an scenario where we've to remove the whitespace between the string. And where we need this squish() helper method which is introduced in Laravel 9 which is not only remove the whitespace from from the beginning and ending of a string it can also remove the whitespace between the string. Check the below code snippet.

<?php
$text = ' Shouts.dev    is  awesome ';
$squished = Str::squish($text);
// which will print "Shouts.dev is awesome"

This also works in a nicer way like below

<?php
$input = '   Hello     world!   ';

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

// output: Hello universe!  

So, we can replace the string and also trim the whitespace at once.

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚