我想將一個0
作爲僅用於db注入的字符串,而不是00
或0000
作爲字符串。PHP爲空:僅將一個0作爲字符串?
$post["content"] = '00';
if (empty($post["content"]) && $post["content"] !== '0')
{
echo "this field must not be empty!";
}
它不會將其作爲錯誤返回。
我該怎麼辦?
我想將一個0
作爲僅用於db注入的字符串,而不是00
或0000
作爲字符串。PHP爲空:僅將一個0作爲字符串?
$post["content"] = '00';
if (empty($post["content"]) && $post["content"] !== '0')
{
echo "this field must not be empty!";
}
它不會將其作爲錯誤返回。
我該怎麼辦?
使用!trim()
代替:
<?php
$post["content"] = '00';
if ($post["content"] !== '0' && !trim($post["content"], '0'))
{
echo "this field must not be empty!";
}
?>
你的測試是錯誤的。
$single ="0";
$double = "00";
var_dump(empty($single)); // true
var_dump(empty($double)); // false
雙零不爲空。
請勿使用empty()
進行驗證。你從頭頂上知道哪些數值被認爲是「空的」?有一些驚喜,這足以讓我避免這個功能。
'不要使用空()用於validation'>如果我知道所有可能的'空()'的價值觀,我不應該太使用它呢?它是表單驗證...爲什麼'empty()'是**糟糕的**? – BlitZ
「0」爲空,「1」不是,也是「00」 - 表單驗證等重要任務的行爲不一致。如果你想檢查非零字符串長度,使用'strlen()'。如果你想強制執行某些內容,那麼正則表達式可能是一個很好的選擇。無論你使用什麼:它應該毫無疑問地解釋自己。 'empty()'失敗了這個約束。 – Sven
即使'empty()'在幾個非複雜條件下可能就足夠了,如果正確使用它。只是不要將這個功能歸咎於所有的罪惡,因爲更多的時候,人類會犯錯而不是功能。 – BlitZ
非常感謝您的回答! – laukok