tags:

views:

452

answers:

6

How can i check to see if a string only contains spaces?

+8  A: 
if (strlen(trim($str)) == 0)

or if you don't want to include empty strings,

if (strlen($str) > 0 && strlen(trim($str)) == 0)
John Knoeller
I'd say `if (strlen(trim($str)) != strlen($str))`
voyager
@voyager: that would determine if the string had _any_ leading or trailing spaces, the question is does it have _only_ spaces.
John Knoeller
@voyager: What about `" hello world "`? In that case `strlen(trim($str))` is 11 and `strlen($str)` is 15, but the string is not *only* made up on spaces.
William Brendel
voyager
Mark
This will be true if your string is empty, ex: $str == "", which you may not want
TravisO
@Travis0: That's already been pointed out, but tarnfeld apparently _did_ want to include empty strings. Still, since people keep wandering by to point it out again, I have edited the answer to make that clear.
John Knoeller
this works fine, thanks :)
tarnfeld
+2  A: 

check if result of trim() is longer than 0

migajek
+5  A: 
echo preg_match('/^ *$/', $string)

Should work.

Enrico Carlesso
yes, regexp is the preferred way for things like this
stereofrog
@stereofrog: I respectfully disagree. Regexes are overkill for something like this, that can be handled perfectly by built in functions.
voyager
That's true, and also maybe builtin functions like shown by John are faster than regexp. But I love regexp, and I use to do everything I can by them, even if not necessary at all. And anyway, I was sure that simplest solutions will have been posted, I just want people not to forget regexp :D
Enrico Carlesso
+2  A: 

Use a regular expression:

$result = preg_match('/^ *$/', $text);

If you want to test for any whitespace, not just spaces:

$result = preg_match('/^\s*$/', $text);
Mark Byers
oh you jerk. wrote the exact same thing as me within 2 seconds :p
Mark
Great @Marks think alike.
voyager
A: 

I think using regexes is overkill, but here's another sol'n anyway:

preg_match('`^\s*$`', $str)
Mark
A: 

another way

preg_match("/^[[:blank:]]+$/",$str,$match);
ghostdog74