If the line contains only spaces?

How can I check if a string contains only spaces?

+24
string php
Feb 28 '10 at 21:34
source share
10 answers
if (strlen(trim($str)) == 0) 

or if you do not want to include blank lines,

 if (strlen($str) > 0 && strlen(trim($str)) == 0) 
+35
Feb 28 '10 at 21:38
source share
 echo preg_match('/^ *$/', $string) 

Must work.

+5
Feb 28 '10 at 21:40
source share

from: stack overflow

If you want to boost, do it on another answer , not this one!




This will be the fastest way:

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

Returns false on an empty string because empty is not empty. 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




as a function:

 function stringIsNullOrWhitespace($text){ return ctype_space($text) || $text === "" || $text === null; } 
+4
Jun 19 '13 at 17:53 on
source share

check if trim () result is longer than 0

+3
Feb 28 '10 at 21:38
source share

Use regex:

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

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

 $result = preg_match('/^\s*$/', $text); 
+3
Feb 28 '10 at 21:40
source share

I think using regular expressions is redundant, but here's another sol'n:

 preg_match('`^\s*$`', $str) 
+3
Feb 28 '10 at 21:42
source share

another way

 preg_match("/^[[:blank:]]+$/",$str,$match); 
+1
Mar 01 '10 at 1:05
source share

Another way, just for playback

 <?php 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: break; default: return false; } } return true; } 
0
Aug 22 '13 at 22:22
source share
 chop($str) === '' 

That should be enough.

0
Apr 07 '14 at 10:01
source share

If you are using Ck-editor, you must do this.

 if( strlen(trim($value,'&nbsp;')) == 0 ){ echo "White space found!" } 
0
Jun 25 '14 at 6:03
source share



All Articles