Detect no characters in a string

1

How do I detect existence of non-characters like this in a string? �*�v��R�<�

    
asked by anonymous 06.06.2014 / 01:05

3 answers

3

"regular" ASCII characters range from hexadecimal 20 to 7F :

Imagecreditsfor Wikimedia Commons .

So, a practical method is to check if all the characters in the string are within this range ASCII, where for that purpose we can make use of a regular expression:

Example where the characters are out of the list:

$string = "�*�v��R�<�";

if (preg_match('/[^\x20-\x7f]/', $string)) {
  echo "Correu mal, chamar função novamente!".PHP_EOL;   // vai entrar aqui
}
else {
  echo "Todos os caracteres são legíveis!".PHP_EOL;
}

Example where the characters are within the list:

$string = "HGKER%(()W(/T%&)WREGDG";

if (preg_match('/[^\x20-\x7f]/', $string)) {
  echo "Correu mal, chamar função novamente!".PHP_EOL;
}
else {
  echo "Todos os caracteres são legíveis!".PHP_EOL;      // vai entrar aqui
}

Examples working on Ideone .

    
26.12.2014 / 21:06
2

To detect characters in a string you can use the preg_match :

$numero = '/(1|2|345|67|7890)/';
$frase = 'abcdefgh ijklmno pqrstu vxz';

echo preg_match($palavra, $frase);

But these characters that you want to identify, have to do with the charset of your bank or your code, probably modifying one of these two characters will no longer appear:

You can set charset in HTML:

>meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

You can set the charset in PHP:

header('Content-Type: text/html; charset=UTF-8');

And you can set the charset in MySQL:

$conn = mysql_connect("localhost", "root", ""); //("servidor", "usuário", "senha" definidos no banco de dados)

mysql_query("SET NAMES 'utf8'");
mysql_query("SET character_set_connection=utf8");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_results=utf8")

And if you're using PDO:

$conn = new \PDO('mysql:host=localhost;dbname=bancoTeste', //dsn
                 'root', //user
                 '123456', //senha
                 array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") // opções PDO
              );
    
06.06.2014 / 01:33