Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 353
Belgin Fish Avatar asked Feb 03 '11 01:02

Belgin Fish


People also ask

How check string is space or not in 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.

Which function in PHP is used to get the length of string?

The strlen() function returns the length of a string.

Is there a limit to string length PHP?

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.

Is \0 included in the size of string?

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.


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 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.

like image 133
Mark Elliot Avatar answered Oct 06 '22 00:10

Mark Elliot


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".

like image 43
cweston Avatar answered Oct 05 '22 23:10

cweston