Skip to content
Advertisement

How do I detect non-ASCII characters in a string?

If I have a PHP string, how can I determine if it contains at least one non-ASCII character or not, in an efficient way? And by non-ASCII character, I mean any character that is not part of this table, http://www.asciitable.com/, positions 32 – 126 inclusive.

So not only does it have to be part of the ASCII table, but it also has to be printable. I want to detect a string that contains at least one character that does not meet these specifications (either non-printable ASCII, or a different character altogether, such as a Unicode character that is not part of that table.

Advertisement

Answer

I found it more useful to detect if any character falls out of the list

if(preg_match('/[^x20-x7e]/', $string))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement