我有一个函数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
}

其他回答

只需使用strlen()函数

if (strlen($s)) {
   // not empty
}

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

return empty($input);

or

return is_string($input);

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

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

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

我需要在PHP中测试一个空字段并使用

ctype_space($tempVariable)

这对我来说很有效。

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

$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
}