簡體   English   中英

檢測字符串是否包含任何數字

[英]Detect if a string contains any numbers

這是 test.php 文件:

$string = 'A string with no numbers';

for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}

// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));

// function
function codeStyle($string) {
    return '<span style="background-color: #eee; font-weight: bold;">' . $string . '</span>';
}

它逐個字符地拆分字符串並檢查該字符是否為數字。

問題:它的 output總是“這個變量包括數字”。 請幫我找出原因。 提示:當我將range(0,9)更改為range(1,9)時,它可以正常工作(但無法檢測到 0)。

使用preg_match()

if (preg_match('~[0-9]+~', $string)) {
    echo 'string with numbers';
}

雖然你不應該使用它,因為它比preg_match()慢得多我會解釋為什么你的原始代碼不起作用:

與數字進行比較時字符串中的非數字字符( in_array()在內部執行)將被評估為0什么是數字。 檢查此示例:

var_dump('A' == 0); // -> bool(true)
var_dump(in_array('A', array(0)); // -> bool(true)

正確的是在這里使用is_numeric()

$keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(is_numeric($string[$i]))  {
       $keyword = 'includes';
       break;
    }
}

或者使用數字的字符串表示:

$keyword = 'doesn\'t include';
// the numbers as stings
$numbers = array('0', '1', '2', /* ..., */ '9');

for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(in_array($string[$i], $numbers)){
       $keyword = 'includes';
       break;
    }
}

你可以使用正則表達式

$message_keyword = preg_match('/\d/', $string) ? 'includes' : 'desn\'t include';

這是因為PHP松散類型比較,你將字符串與整數進行比較,因此PHP內部將此字符串轉換為整數,並且字符串中的所有字符將被轉換為0。

修復代碼的第一步是創建一個字符串數組而不是整數:

$numbers = array_map(function($n){ return (string)$n; }, range(0,9));
for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char,$numbers)?'includes' : 'doesn\'t include';
}

這將修復您的情況,但不會按預期工作,因為$message_keyword會在每個循環中被覆蓋,因此將僅接收最后一個字符的消息。 如果您的目標只是檢查字符串是否包含數字,您可以在遇到第一個數字后停止檢查:

$message_keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    if(in_array($char, $numbers)) {
        $message_keyword = 'includes';
        break; //found, no need to check next
    }   
}

要以更緊湊的形式使用所有邏輯,請使用其他人之前發布的常規表達式。

更好的方法是使用正則表達式

<?php
    if (preg_match('#[0-9]#',$string)){
        $message_keyword = 'includes';
    }
    else{
        $message_keyword = 'desn\'t include';
    }  
?>
array range ( mixed $start , mixed $end [, number $step = 1 ] )

如果給出step值,它將用作序列中elements之間的增量。 step應作為positive number給出。 如果未指定 ,則步驟將默認為1

在您的情況下,您沒有提到第三個參數,這就是它始終設置為1

請參閱此處的手冊

大約 9 年后回答這個問題有點晚了,但是如果你想檢測整數(而不是浮點數),沒有什么比ctype_digit更好的了。 使用此 function 檢測帶有小數點或其他類型的浮點數將導致返回false

<?php
$number = "123";
$notNumber = "123abc";
var_dump(ctype_digit($number));
var_dump(ctype_digit($notNumber));
?>

Output

bool(true)
bool(false)

暫無
暫無

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

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