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

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


当前回答

PHP有一个内置的函数叫做empty() 测试是通过打字来完成的 如果(空字符串($)){…} 参考php.net: php 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代表任何非空白字符

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

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

如果你有一个字段,即serial_number,并希望检查为空,那么

$serial_number = trim($_POST[serial_number]);
$q="select * from product where user_id='$_SESSION[id]'";
$rs=mysql_query($q);
while($row=mysql_fetch_assoc($rs)){
if(empty($_POST['irons'])){
$irons=$row['product1'];
}

通过这种方式,您可以使用另一个空函数检查循环中的所有字段