Check if the string is just a space?

Possible duplicate:
If the line contains spaces?

I do not want to change the line and do not want to check if it contains a space. I want to check if the whole line is ONLY a space. What is the best way to do this?

+41
php
Jun 07 '10 at 19:06
source share
4 answers

This will be the fastest way:

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

Returns false on an empty string because empty is not white space. If you need to include an empty string, you can add || $str == '' || $str == '' This will still lead to faster execution than regular expression or trimming.

ctype_space

+89
Jun 07 '10 at 19:16
source share
— -

since trim returns a string with a space removed, use this to check

 if (trim($str) == '') { //string is only whitespace } 
+34
Jun 07 '10 at 19:08
source share
 if( trim($str) == "" ) // the string is only whitespace 

That should do the trick.

+9
Jun 07 '10 at 19:08
source share

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

change * to + if empty is not allowed

+3
Jun 07 '10 at 19:08
source share



All Articles