How to remove all unwanted spaces from a String – Laravel

There are numerous methods to remove unwanted spaces from a String. Laravel uses the squish() method to remove all remove extra whitespaces and extra characters from a string. Suppose a long string has multiple consecutive spaces, tab and newline characters you need to format. You can simply pass the squish function to that string as shown below. 

$para = "This   is a  \n  \t string  with   spaces.";

str($para)->squish();

The function gives the output shown below.

This is a string with spaces.

This method will use the php string function preg_replace() in Laravel to replace or remove the set of unwanted characters or spaces from a String. The built-in Laravel function works as shown below. 

public static function squish($value)

{

return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', preg_replace('~^[\s\x{FEFF}]+|[\s\x{FEFF}]+$~u', '', $value));

}

The preg_replace() function is useful for removing multiple whitespaces or even consecutive spaces from a string. 

In the code snippet above, the first use of it removes all leading and trailing whitespaces and BOM (byte order mark) characters. 

The second use of preg_replace will replace all special fillers and unwanted whitespaces with a single space.

Leave a Comment