既然PHP是一种动态语言,那么检查所提供字段是否为空的最佳方法是什么?
我要确保:
Null被认为是空字符串 只有空格的字符串被认为是空的 那个“0”不是空的
这是我目前得到的:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
一定有更简单的方法吧?
既然PHP是一种动态语言,那么检查所提供字段是否为空的最佳方法是什么?
我要确保:
Null被认为是空字符串 只有空格的字符串被认为是空的 那个“0”不是空的
这是我目前得到的:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
一定有更简单的方法吧?
当前回答
用这个:
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
其他回答
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
旧帖子,但有人可能会像我一样需要它;)
if (strlen($str) == 0){
do what ever
}
用变量替换$str。 NULL和""在使用strlen时都返回0。
如果我错了,我会谦虚地接受,但我在自己的一端进行了测试,发现下面的代码可以用于测试字符串(0)""和NULL值变量:
if ( $question ) {
// Handle success here
}
这也可以反过来测试是否成功:
if ( !$question ) {
// Handle error here
}
没有更好的方法,但由于这是一个你经常做的操作,你最好自动化这个过程。
大多数框架都提供了一种使参数解析变得简单的方法。你可以为此创建自己的对象。举个简单的例子:
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony大量使用这种糖。
但是您所谈论的远不止这些,这里有“// Handle”错误 ”。您混合了两项工作:获取数据和处理数据。这完全不一样。
您还可以使用其他机制来验证数据。同样,框架可以向您展示最佳实践。
创建表示表单数据的对象,然后附加流程并返回到它。这听起来比破解一个快速的PHP脚本要费时得多(这是第一次),但是它是可重用的、灵活的,而且更不容易出错,因为使用普通PHP进行表单验证往往很快就会变成spaguetti代码。
用这个:
// check for null or empty
if (empty($var)) {
...
}
else {
...
}