0

I would like to check and see if a given string contains any characters or if it is just all white space. How can I do this?

I have tried:

$search_term= " ";

if (preg_match('/ /',$search_term)) {
    // do this
}

But this affects search terms like this as well:

$search_term= "Mark Zuckerburg";

I only want a condition that checks for all white space and with no characters.

Thanks!

user2320500
  • 169
  • 3
  • 10
  • trim it. if the length of the trimmed string is 0 then it's of all white spaces. has some other characters otherwise :) – Fallen Jul 09 '13 at 19:40
  • possible duplicate of [How to check if there are only spaces in string in PHP?](http://stackoverflow.com/questions/1754393/how-to-check-if-there-are-only-spaces-in-string-in-php) – Felix Kling Jul 09 '13 at 19:46

2 Answers2

3

Use trim():

if(trim($search_term) == ''){
    //empty or white space only string
    echo 'Search term is empty';
}

trim() will cut whitespace from both start and end of a string - so if the string contains only whitespace trimming it will return empty string.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
3

ctype_space does this.

$search_term = " ";

if (ctype_space($search_term)) {
    // do this
}

The reason your regular expression doesn’t work is that it’s not anchored anywhere, so it searches everywhere. The right regular expression would probably be ^\s+$.

The difference between ctype_space and trim is that ctype_space returns false for an empty string. Use whatever’s appropriate. (Or ctype_space($search_term) || $search_term === ''…)

Ry-
  • 218,210
  • 55
  • 464
  • 476