Belgin Fish
Belgin Fish

Reputation: 19837

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

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

Upvotes: 8

Views: 20466

Answers (3)

Mohammed Fayoumi
Mohammed Fayoumi

Reputation: 11

You can simply check if it is empty without white-spaces using this comparison:

if(!strlen(trim($text))){
  // To do: 
}

Reference: PHP type comparison tables

Upvotes: 0

cweston
cweston

Reputation: 11637

Also, you can use trim and empty.

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

From the PHP docs:

The following things are considered to be PHP Empty:

  • "" (an empty string)
  • array() (an empty array)

Therefore trimming all whitespace will give you your desired result when combined with empty. However keep in mind that empty will return true for strings of "0".

Upvotes: 3

Mark Elliot
Mark Elliot

Reputation: 77044

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 strings that consist of just spaces, regardless of how many there are.

If you're validating inputs, you might want to think about other degenerate cases, too, like someone entering just an underscore, or other unsuitable input. If you tell us more about the situation you're trying to deal with we might be able to provide more robust checking.

Upvotes: 30

Related Questions