PHP - ctype_digit() 函式



PHP 字元型別檢查ctype_digit() 函式用於檢查提供的字串是否僅包含數字字元。“數字”字元指的是從 0 到 9 的十進位制數字。例如,在字串“1234”中,所有字元都是數字。

如果字串中的每個字元都是十進位制數字,則此函式返回布林值true,否則返回false。如果提供的字串為空(""),則該函式始終返回false

語法

以下是 PHP 字元型別檢查ctype_digit() 函式的語法:

ctype_digit (mixed $text): bool

引數

此函式接受以下引數:

  • text(必需) - 需要檢查或測試的字串。

返回值

如果 text 中的每個字元都是十進位制數字,則此函式返回“true”,否則返回“false”。

示例 1

如果提供的文字包含十進位制數字,則 PHP ctype_digit() 函式將返回true

<?php
   $text = "1232";
   echo "The given text: ".$text;
   #using ctype_digit() function
   echo "\nDoes the text contain only decimal digits? ";
   var_dump(ctype_digit($text));
?>

輸出

這將產生以下結果:

The given text: 1232
Does the text contain only decimal digits? bool(true)

示例 2

如果提供的文字不包含十進位制數字,則 PHP ctype_digit() 函式將返回false

<?php
   $text = "Tutorialspoint";
   echo "The given text: ".$text;
   #using ctype_digit() function
   echo "\nDoes the text contain only decimal digits? ";
   var_dump(ctype_digit($text));
?>

輸出

執行上述操作後,將顯示以下輸出:

The given text: Tutorialspoint
Does the text contain only decimal digits? bool(false)

示例 3

如果提供的文字或字串為空(""),則此函式將始終返回false

<?php
   $text = " ";
   echo "The given text: ".$text;
   #using ctype_digit() function
   echo "\nDoes the text contains only decimal digits? ";
   var_dump(ctype_digit($text));
?>

輸出

執行上述程式後,它將返回“false”:

The given text:
Does the text contain only decimal digits? bool(false)

示例 4

檢查多個字串(文字)。

在以下示例中,我們宣告一個包含多個文字的陣列,並將使用ctype_alnum() 函式檢查每個字串以確定它們是否為字母數字:

<?php
   $texts = array('123432', 'hello', '12hi');
   echo "The given Strings are: ";
   foreach($texts as $text){
	   echo $text." ";
   }
   foreach($texts as $text){
	   if(ctype_digit($text)){
		   echo "\nThe string '$text' contains only decimal digits.";
	   }
	   else{
		   echo "\nThe string '$text' does not contain only decimal digits.";
	   }
   }
?>

輸出

以下是上述程式的輸出:

The given Strings are: 123432 hello 12hi
The string '123432' contains only decimal digits.
The string 'hello' does not contain only decimal digits.
The string '12hi' does not contain only decimal digits.
php_function_reference.htm
廣告