bgo*_*lci 214 php string validation
我有一个函数isNotEmpty,如果字符串不为空则返回true,如果字符串为空则返回false.我发现如果我通过它传递一个空字符串就无法正常工作.
function isNotEmpty($input)
{
$strTemp = $input;
$strTemp = trim($strTemp);
if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)"
{
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
使用isNotEmpty验证字符串是完成的:
if(isNotEmpty($userinput['phoneNumber']))
{
//validate the phone number
}
else
{
echo "Phone number not entered<br/>";
}
Run Code Online (Sandbox Code Playgroud)
如果字符串是空的,否则不会执行,我不明白为什么,请有人请说明这一点.
cle*_*tus 300
实际上简单的问题 更改:
if (strTemp != '')
Run Code Online (Sandbox Code Playgroud)
至
if ($strTemp != '')
Run Code Online (Sandbox Code Playgroud)
可以说你可能也想把它改成:
if ($strTemp !== '')
Run Code Online (Sandbox Code Playgroud)
因为PHP的自动类型转换,!= ''
如果传递的是数字0和其他一些情况,则返回true .
你不应该使用内置的empty()函数; 请参阅注释和PHP类型比较表.
小智 30
PHP有一个内置函数,称为empty()
测试是通过输入
if(empty($string)){...}
引用php.net:php empty来完成的
Geo*_*pty 20
我总是使用正则表达式来检查一个空字符串,可以追溯到CGI/Perl天,也可以使用Javascript,所以为什么不使用PHP,例如(尽管未经测试)
return preg_match('/\S/', $input);
Run Code Online (Sandbox Code Playgroud)
其中\ S表示任何非空白字符
Bjö*_*örn 18
在函数的if子句中,您指的是一个不存在的变量'strTemp'.但是'$ strTemp'确实存在.
但PHP已经有一个空() - 函数可用,为什么要自己做?
if (empty($str))
/* String is empty */
else
/* Not empty */
Run Code Online (Sandbox Code Playgroud)
来自php.net:
返回值
如果var具有非空和非零值,则返回FALSE.
以下内容被认为是空的:
Run Code Online (Sandbox Code Playgroud)* "" (an empty string) * 0 (0 as an integer) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class)
tro*_*skn 14
PHP将空字符串计算为false,因此您只需使用:
if (trim($userinput['phoneNumber'])) {
// validate the phone number
} else {
echo "Phone number not entered<br/>";
}
Run Code Online (Sandbox Code Playgroud)
jus*_*tyy 10
只需使用strlen()函数
if (strlen($s)) {
// not empty
}
Run Code Online (Sandbox Code Playgroud)
我只是编写了自己的函数,用于类型检查的is_string和用于检查长度的strlen。
function emptyStr($str) {
return is_string($str) && strlen($str) === 0;
}
print emptyStr('') ? "empty" : "not empty";
// empty
Run Code Online (Sandbox Code Playgroud)
编辑:您还可以使用修剪功能来测试字符串是否也为空。
is_string($str) && strlen(trim($str)) === 0;
Run Code Online (Sandbox Code Playgroud)