處理使用者輸入時,驗證資料以確保其完整性至關重要。一個常見的驗證任務是檢查變數是否表示整數。 PHP 為此提供了 is_int() 函數,但它可能不會總是產生所需的結果。
使用 is_int() 可能會傳回誤報對於看起來是整數但函數無法辨識的值。例如,考慮使用者輸入“1”作為頁碼的情況:
<code class="php">$page = $_GET['p'];</code>
在這種情況下,$page 將被分配字串“1”,這將導致 is_int($page ) 傳回 false。
要可靠地檢查變數是否為整數,請考慮使用提供更準確結果的替代方法:
FILTER_VALIDATE_INT 過濾器可用來驗證整數輸入:
<code class="php">if (filter_var($page, FILTER_VALIDATE_INT) === false) { // Not an integer }</code>
輸出:
TEST -1: -1 (type:integer) Your variable is an integer ✔ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔
<code class="php">if (strval($page) !== strval(intval($page))) { // Not an integer }</code>
輸出:
TEST -1: -1 (type:integer) Your variable is an integer ✔ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔3. CTYPE_DIGIT 方式使用ctype_digit 函數,可以檢查正數和0:
<code class="php">if (!ctype_digit(strval($page))) { // Not an integer }</code>
輸出:
TEST -1: -1 (type:integer) # Your variable is not an integer ✘ TEST 0 : 0 (type:integer) is an integer ✔ TEST 1 : 42 (type:integer) is an integer ✔ TEST 2 : 4.2 (type:double) is not an integer ✘ TEST 3 : 0.42 (type:double) is not an integer ✘ TEST 4 : 42 (type:double) is an integer ✔ TEST 5 : 42 (type:string) is an integer ✔ TEST 6 : a42 (type:string) is not an integer ✘ TEST 7 : 42a (type:string) is not an integer ✘ TEST 8 : 36 (type:integer) is an integer ✔ TEST 9 : 1337 (type:double) is an integer ✔4。 REGEX方式正規表示式也可以用來驗證整數:
<code class="php">if (!preg_match('/^-?\d+$/', $page)) { // Not an integer }</code>
輸出:
以上是如何可靠地檢查 PHP 中的變數是否代表整數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!