PHP - ctype_print() 函式



PHP 字元型別檢查ctype_print()函式檢查字串是否只包含可列印字元,包括字母、數字、標點符號和空格。不可列印字元,例如“\n”、“\t”和“\r”,不被認為是可列印字元。

如果字串僅由可列印字元組成,則此函式返回布林值true;否則,返回false。如果字串為空(""),則此函式也返回false

語法

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

ctype_print(mixed $text): bool

引數

此函式接受以下引數:

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

返回值

如果 text 中的每個字元都能實際產生輸出(包括空格),則此函式返回“true”;否則返回“false”。

示例 1

以下是 PHP ctype_print()函式的基本示例:

<?php
   $string = "Tutorialspoint\n\r";
   echo "The given string is: $string";
   echo "\nDoes the '$string' consist of all the printable characters? ";
   var_dump(ctype_print($string));
?>

輸出

上述程式產生以下輸出:

The given string is: Tutorialspoint

Does the 'Tutorialspoint
' consist of all the printable characters? bool(false)

示例 2

如果給定的字串 (text) 不包含所有可列印字元,則 PHP ctype_print()函式將返回false

<?php
   $string = "Tutorialspoint1332";
   echo "The given string is: $string";
   echo "\nDoes the '$string' consist of all the printable characters? ";
   var_dump(ctype_print($string));
?>

輸出

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

The given string is: Tutorialspoint1332
Does the 'Tutorialspoint1332' consist of all the printable characters? bool(true)

示例 3

如果給定的字串為空(""),此函式始終返回false

<?php
   $string = "";
   echo "The given string is: $string";
   echo "\nDoes the '$string' consist of all the printable characters? ";
   var_dump(ctype_print($string));
?>

輸出

執行上述程式後,將生成以下輸出:

The given string is:
Does the '' consist of all the printable characters? bool(false)

示例 4

在下面的示例中,我們建立一個包含多個字串值的字串陣列,並在 foreach 迴圈中使用 PHP ctype_print()函式檢查每個字串是否僅由可列印字元組成:

<?php
   $strings = array("asdf\n\r\t", "hello123", 'fooo#int%@');
   echo "The given strings are: ";
   foreach ($strings as $text){
	   echo $text." ";
   }
   foreach ($strings as $test) {
      if (ctype_print($test)) {
         echo "\nThe string '$test' consists of all the printable characters.";
      }else {
         echo "\nThe string '$test' does not consist of all the printable characters.";
      }
   }
?>

輸出

以下是上述程式的輸出:

The given strings are: asdf
         hello123 fooo#int%@
The string 'asdf
        ' does not consist of all the printable characters.
The string 'hello123' consists of all the printable characters.
The string 'fooo#int%@' consists of all the printable characters.
php_function_reference.htm
廣告