What is the ctype_cntrl method in PHP?

The ctype_cntrl method can be used to check if all the characters in the text are control characters.

Syntax

ctype_cntrl(mixed $text): bool

This method returns a Boolean value.

The control characters are

  • \0: Null character.
  • \n: New line character.
  • \b: Backspace character.
  • \t: Horizontal tab character.
  • \v: Vertical tab character.
  • \f: Form field character.
  • \r: Carriage return character.
  • \e: Escape character.

Read more about control characters here.

Example

<?php
$str = "\t";
printIsControlCharacters($str);
$str = "\n\r\t";
printIsControlCharacters($str);
$str = "123";
printIsControlCharacters($str);
$str = "a";
printIsControlCharacters($str);
function printIsControlCharacters($str){
echo "The string is: ". $str. "\n";
echo "Is Control Char: ";
var_dump(ctype_cntrl($str));
echo "---------\n";
}
?>

In the code above:

  • We have used the ctype_cntrl method to check if the string contains only control characters.

  • For the string \t and \n\r\t, the ctype_cntrl returns true.

  • For the string 123 and a, the ctype_cntrl method returns false because the string contains characters that are not control characters.

Free Resources