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.

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.


as a function:

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

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);

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

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

another way


chop($str) === ''

This should be enough.

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

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

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;

in my program it worked well like this,

$comment = $_POST['comment'];
$commentcheck = trim($comment);

if (empty($commentcheck)) 
    //instruction with $comment

trim() function just delete all spaces from $comment string. Then it check if it is empty. So in this if statement you have to show an error message then use else to code whatever you want to write.

Need Your Help

Insert 6000 rows in Couchbase, but not stored success

.net memcached generic-list couchbase

I generated 6000 objects in List, and stored List into Couchbase with memcached, but the Store method returned "false" without any messages, I don't know why 6000 rows data can not be stored but 2000

Issue when trying to run WEBrick and Rails

ruby-on-rails webrick

Going through the Lynda training for Ruby on Rails and got to the point where I am starting the WEBrick sever via the rails s command. I am in the same directory as the video /Users/myuser/Sites/