簡體   English   中英

無法確定字符串當前是否為整數

[英]unable to determine if a string is currently an integer or not

以下功能使我發瘋。 地球上的100x如何等於100,然后將100x報告為整數?
對於我的一生,我無法弄清楚。 您可以復制並粘貼整個內容,然后自己查看。
我在這里某處缺少一個簡單的要點,請大家幫幫我。

function blp_int($val) {
    $orgval = $val;
    $num = (int)$val;    
    echo "<li><font color=red>val: ". $val . " is being checked to see if it's an integer or not";
    echo "<li><font color=red>orgval: ". $orgval ;
    echo "<li><font color=red>num: ". $num ;
    if ($orgval==$num) {
        echo "<li><font color=red><b>YES IT IS! the [{$orgval}] is equal to [{$num}]</b>";
        return true;
    }
    return false;
}

if (blp_int("100"))
{
    echo "<h1>100 is an integer!</h1>";
}
else
{
    echo "<h1>100 is NOT an integer!</h1>";
}

if (blp_int("100x"))
{
    echo "<h1>100x is an integer!</h1>";
}
else
{
    echo "<h1>100x is NOT an integer!</h1>";
}

上面的代碼,運行時返回以下內容;

val: 100 is being checked to see if it's an integer or not
orgval: 100
num: 100
YES IT IS. the [100] is equal to [100]
100 is an integer!

val: 100x is being checked to see if it's an integer or not
orgval: 100x
num: 100
YES IT IS. the [100x] is equal to [100]
100x is an integer!

我可以通過添加以下內容來糾正這種情況

    if (!is_numeric($val))
    {
        return false;
    }

馬上就到了blp_int函數的頂部,但是,..我仍然非常想知道為什么地球上php認為100x = 100是相等的。

本例所示 ,將100x轉換為整數會將其轉換為100 由於未使用嚴格比較 ,因此'100x' == 100為true。 PHP從中刪除x ,得到100

您可以使用嚴格比較(也可以比較類型),這樣'100x' === 100將返回false。 使用它,每當將字符串與整數進行比較時,它將返回false。


根據您的編輯: is_numeric可能不是最可靠的,因為它將對格式化為字符串的數字(例如'100'返回true。 如果希望數字為整數 (而不是字符串),則可以使用is_integer 我不太確定您到底在做什么,但我想我要添加此注釋。

我認為您應該在IF中使用三個等號:

if ($orgval===$num) {

否則,PHP將值100x強制轉換為100並且100=100

文檔:比較運算符

您要做什么支票? 有幾種方法可以解決:

if (preg_match('!^[0-9]+$!', $input))

if (intval($input) == $input)

if (intval($input) === $input)

if ('x'.intval($input) === 'x'.$input)

這取決於您要檢查它是否為整數的緊密程度。 是否需要首先trim()它有關系嗎?

可以將其強制轉換為int或嘗試http://php.net/manual/en/function.ctype-digit.php 如果還需要===

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM