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

其他回答

如果你有一个字段,即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'];
}

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

只需使用strlen()函数

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

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

if (trim($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中测试一个空字段并使用

ctype_space($tempVariable)

这对我来说很有效。