Verify string has a length greater than 0 and is not space in PHP

How can I verify that a given string is not a space and is longer than 0 characters using PHP?

+4
source share
2 answers

Assuming your string is in $string :

 if(strlen(trim($string)) > 0){ // $string has at least one non-space character } 

Note that this will not allow any lines consisting of just spaces, no matter how many there are.

If you are checking for data entry, you might think of other degenerative cases, such as someone entering only an underscore or other inappropriate input. If you tell us more about the situation you are trying to deal with, we could provide a more reliable verification.

+22
source

Alternatively, you can use trim and empty.

 $input = trim($string); if(empty($input)) { doSomething(); } 

From the PHP docs:

The following things are considered PHP Empty :

  • "" (empty line)
  • array () (empty array)

Therefore, trimming all spaces will give you the desired result, combined with empty. However, keep in mind that empty will return true for the strings "0".

+3
source

Source: https://habr.com/ru/post/1338187/


All Articles