tags:

views:

180

answers:

4

Possible Duplicate:
If string only contains spaces?

I do not want to change a string nor do I want to check if it contains white space. I want to check if the entire string is ONLY white space. What the best way to do that?

+11  A: 

since trim returns a string with whitespace removed, use that to check

if (trim($str) == '')
{
 //string is only whitespace
}
MANCHUCK
Hmm, indeed, faster then the preg_* route..
Wrikken
+1 for a non regex solution. Not that there is anything wrong with regex.
Neil Aitken
Just remember that trim will turn anything you pass into it into a string. i.e (trim(false) == '') will return true, which may fall outside the original poster's requirements (but it most likely fine)
Alan Storm
+2  A: 

preg_match('/^\s*$/',$string)

change * to + if empty is not allowed

Wrikken
What does `\s` mean? Non white space?
John Isaacks
`\s` means whitespace
Dan McGrath
@John, as said, whitespace, perhaps your confusing the character class ^ ([^p] = anything not 'p') with '^p' (= string has to start with p)
Wrikken
`\s` is "whitespace," `\S` is "not whitespace"
Justin Johnson
I'm voting down only because you should avoid regex only when needed. For something simple as this, build in PHP functions are the way to go
MANCHUCK
@Wrikken, yes thanks. I have never used the \s char, plus I think regex is much easier to write than to read.
John Isaacks
Wrikken
+4  A: 
if( trim($str) == "" )
    // the string is only whitespace

This should do the trick.

svens
+10  A: 

This will be the fastest way:

$str = '      ';
if (ctype_space($str)) {

}

Returns false on empty string because empty is not white-space. If you need to include an empty string, you can add || $str == '' This will still result in faster execution than regex or trim.

ctype_space

webbiedave
Wow, I didn't imagine it could get much simpler than the trim, but I guess it can. +1 for a function I've never seen or used.
epalla
+1 This addresses exactly what the problem is.
Justin Johnson