Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If string only contains spaces?

Tags:

string

php

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

like image 478
tarnfeld Avatar asked Feb 28 '10 21:02

tarnfeld


People also ask

How do I check if a string contains only spaces?

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.

How do you check if a string is only spaces Python?

Python isspace() method is used to check space in the string. It returna true if there are only whitespace characters in the string. Otherwise it returns false. Space, newline, and tabs etc are known as whitespace characters and are defined in the Unicode character database as Other or Separator.

How do I check if a string contains only spaces in PHP?

PHP | ctype_space() Function A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False.


7 Answers

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

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

if (strlen($str) > 0 && strlen(trim($str)) == 0) 
like image 85
John Knoeller Avatar answered Sep 24 '22 21:09

John Knoeller


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; } 
like image 22
2 revs Avatar answered Sep 22 '22 21:09

2 revs


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

Should work.

like image 39
Enrico Carlesso Avatar answered Sep 23 '22 21:09

Enrico Carlesso


check if result of trim() is longer than 0

like image 20
migajek Avatar answered Sep 22 '22 21:09

migajek


Use a regular expression:

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

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

$result = preg_match('/^\s*$/', $text);
like image 23
Mark Byers Avatar answered Sep 24 '22 21:09

Mark Byers


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

preg_match('`^\s*$`', $str)
like image 44
mpen Avatar answered Sep 24 '22 21:09

mpen


another way

preg_match("/^[[:blank:]]+$/",$str,$match);
like image 20
ghostdog74 Avatar answered Sep 24 '22 21:09

ghostdog74