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
2010-02-28 21:38:17
I'd say `if (strlen(trim($str)) != strlen($str))`
voyager
2010-02-28 21:39:31
@voyager: that would determine if the string had _any_ leading or trailing spaces, the question is does it have _only_ spaces.
John Knoeller
2010-02-28 21:42:28
@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
2010-02-28 21:43:11
voyager
2010-02-28 23:01:59
Mark
2010-03-01 01:21:34
This will be true if your string is empty, ex: $str == "", which you may not want
TravisO
2010-03-01 04:08:57
@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
2010-03-01 04:18:17
this works fine, thanks :)
tarnfeld
2010-03-13 12:55:11
@stereofrog: I respectfully disagree. Regexes are overkill for something like this, that can be handled perfectly by built in functions.
voyager
2010-03-01 16:30:23
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
2010-03-01 17:03:34
+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
2010-02-28 21:40:25
A:
I think using regexes is overkill, but here's another sol'n anyway:
preg_match('`^\s*$`', $str)
Mark
2010-02-28 21:42:10