我有一个函数isNotEmpty,如果字符串不是空的,返回true,如果字符串是空的,返回false。我发现,如果我传递一个空字符串,它是不工作的。

function isNotEmpty($input) 
{
    $strTemp = $input;
    $strTemp = trim($strTemp);

    if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)"
    {
         return true;
    }

    return false;
}

使用isNotEmpty对字符串进行验证:

if(isNotEmpty($userinput['phoneNumber']))
{
    //validate the phone number
}
else
{
    echo "Phone number not entered<br/>";
}

如果字符串是空的,否则不执行,我不明白为什么,有人能解释一下吗?


当前回答

这里有一个简短的方法来检查字符串是否为空。

$input; //Assuming to be the string


if(strlen($input)==0){
return false;//if the string is empty
}
else{
return true; //if the string is not empty
}

其他回答

PHP将空字符串计算为false,所以你可以简单地使用:

if (trim($userinput['phoneNumber'])) {
  // validate the phone number
} else {
  echo "Phone number not entered<br/>";
}

我总是使用正则表达式来检查空字符串,可以追溯到CGI/Perl的日子,也与Javascript,所以为什么不与PHP以及,例如(尽管未经测试)

return preg_match('/\S/', $input);

其中\S代表任何非空白字符

这是一个简短而有效的解决方案,正是你正在寻找的:

return $input > null ? 'not empty' : 'empty' ;

你可以简单地转换为bool,不要忘记处理零。

function isEmpty(string $string): bool {
    if($string === '0') {
        return false;
    }
    return !(bool)$string;
}

var_dump(isEmpty('')); // bool(true)
var_dump(isEmpty('foo')); // bool(false)
var_dump(isEmpty('0')); // bool(false)

你有答案,但在你的情况下,你可以用

return empty($input);

or

return is_string($input);