• Reading time ~ 1 min
  • 19.10.2023

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:

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297