Reputation: 19837
How can I verify that a given string is not a space, and is longer than 0 characters using PHP?
Upvotes: 8
Views: 20466
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
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:
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
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