If string only contains spaces?

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


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

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

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

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

Should work.

check if result of trim() is longer than 0

Use a regular expression:

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

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

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

from: http://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.


as a function:

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

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

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

another way


Another way, just for play

function is_space_str($str) {
    for($i=0,$c=strlen($str);$i<$c;$i++) {
        switch (ord($str{$i})) {
            case 21: 
            case 9:
            case 10: 
            case 13: 
            case 0:
            case 11: 
            case 32: 
                return false;

    return true;

chop($str) === ''

This should be enough.

If you are using Ck-editor then you should do this

if( strlen(trim($value,'&nbsp;')) == 0 ){
    echo "White space found!"

Need Your Help

Netbeans created Jar does not work, but inside IDE program works

java file netbeans jar

The Netbeans created Jar does not work, but inside the IDE program it works perfectly.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.