How can I verify that a given string is not a space, and is longer than 0 characters using PHP?
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.
The strlen() function returns the length of a string.
Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.
A string in C language is an array of characters that is terminated with a null character (\0). The string length is the number of characters in a string. In the string length '\0,' a character is not counted.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With