How to remove all extra spaces in a string with Laravel
Published on by Eric L. Barnes
Let's say you have a paragraph of text with all sorts of weird formatting. Maybe it's from someone copying and pasting text into your CMS, or it's just in a weird state. Something like this:
$paragraph = "hello this is a test \n \t just a test and stuff ";
As you can see, it has extra spaces, a newline character, a tab character, and just oddly formatted.
Laravel provides a great solution to this called the squish
method on the String helpers.
str($paragraph)->squish();
After running it through squish
you'll get all that extra stuff removed:
"hello this is a test just a test and stuff"
Under the hood here is what this method actually does:
/** * Remove all "extra" blank space from the given string. * * @param string $value * @return string */public static function squish($value){ return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', preg_replace('~^[\s\x{FEFF}]+|[\s\x{FEFF}]+$~u', '', $value));}
Here is an explanation:
- The first
preg_replace
removes leading and trailing white spaces or BOM characters. - The second
preg_replace
replaces one or more consecutive white spaces or special fillers with a single space.
This ensures that you get a string with no extra white spaces.
Prefer to see a video, here is a short Reel I made for the @laravelnews Instagram page covering this:
Eric is the creator of Laravel News and has been covering Laravel since 2012.