PHP - ctype_alnum() 函式



PHP 字元型別檢查ctype_alnum()函式用於檢查給定文字中的字元是否為字母數字字元。“字母數字”字元指字母或數字。例如,字串“abC19y”包含字母數字字元。

如果文字中的每個字元都是字母或數字,則此函式返回布林值true;否則,返回false。如果提供的文字為空(),則始終返回false

語法

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

ctype_alnum (mixed $text): bool

引數

此函式接受以下引數:

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

返回值

如果文字中的每個字元都是字母或數字,則此函式返回“true”,否則返回“false”。

示例 1

如果給定的文字是“字母數字”文字,則PHP ctype_alnum()函式將返回true

<?php
   $text = "Hello21";
   echo "The given text: ".$text;
   #using alnum() function
   echo "\nIs the text is alphanumeric? ";
   var_dump(ctype_alnum($text));
?>

輸出

上述程式將產生以下結果:

The given text: Hello21
Is the text is alphanumeric? bool(true)

示例 2

如果給定的字串不是字母數字字串,則PHP ctype_alnum()函式返回false

<?php
   $text = "@Hello#^";
   echo "The given text: ".$text;
   #using alnum() function
   echo "\nIs the text is alphanumeric? ";
   var_dump(ctype_alnum($text));
?>

輸出

執行上述程式後,將顯示以下輸出:

The given text: @Hello#^
Is the text is alphanumeric? bool(false)

示例 3

檢查多個字串(文字)。

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

<?php
   $texts = array('Tutorialspoint', 'tutorix!@13#');
   echo "The given Strings are: ";
   foreach($texts as $text){
	   echo $text." ";
   }
   foreach($texts as $text){
	   if(ctype_alnum($text)){
		   echo "\nThe string '$text' is an alphanumeric.";
	   }
	   else{
		   echo "\nThe string '$text' is not an alphanumeric.";
	   }
   }
?>

輸出

這將產生以下輸出:

The given Strings are: Tutorialspoint tutorix!@13#
The string 'Tutorialspoint' is an alphanumeric.
The string 'tutorix!@13#' is not an alphanumeric.

示例 4

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

<?php
   $text = "";
   echo "The given Strings are: ".$text;
   echo "\nIs the '$text' is an alphanumeric? ";
   var_dump(ctype_alnum($text));
?>

輸出

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

The given Strings are:
Is the '' is an alphanumeric? bool(false)
php_function_reference.htm
廣告