If string only contains spaces?

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


Solution 1:

if (strlen(trim($str)) == 0)

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

if (strlen($str) > 0 && strlen(trim($str)) == 0)

Solution 2:

from: https://stackoverflow.com/a/2992388/160173

If you want to upvote, do it on the other answer, not this one!


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


as a function:

function stringIsNullOrWhitespace($text){
    return ctype_space($text) || $text === "" || $text === null;
}

Solution 3:

echo preg_match('/^ *$/', $string)

Should work.