Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php removing excess whitespace

Tags:

php

I'm trying to remove excess whitespace from a string like this:

hello        world

to

hello world

Anyone has any idea how to do that in PHP?

like image 804
Patrick Avatar asked Nov 29 '10 02:11

Patrick


People also ask

How do I trim a space in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do I remove extra white spaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

What is whitespace in PHP?

More Detail. The ctype_space() function in PHP check for whitespace character(s). It returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.


2 Answers

With a regexp :

preg_replace('/( )+/', ' ', $string);

If you also want to remove every multi-white characters, you can use \s (\s is white characters)

preg_replace('/(\s)+/', ' ', $string);
like image 91
Vincent Savard Avatar answered Sep 29 '22 06:09

Vincent Savard


$str = 'Why   do I
          have  so much white   space?';

$str = preg_replace('/\s{2,}/', ' ', $str);

var_dump($str); // string(34) "Why do I have so much white space?"

See it!

You could also use the + quantifier, because it always replaces it with a . However, I find {2,} to show your intent clearer.

like image 20
alex Avatar answered Sep 29 '22 07:09

alex