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

Viewed 51516

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.

9 Answers

I benchmarked the suggested functions as I need this check for batch processing of shorter (1000 characters max) strings. I tested 10k iterations of 30 different strings (empty, short, longer, ascii, accents, japanese, emoji, non-ascii start, non-ascii end etc). Here are the rough results:

mb_check_encoding: 95ms average. Performance degrades way faster than preg_match and ctype as the strings get longer (1MB+).

mb_check_encoding($input, 'ASCII');

preg_match: 85ms average. Decently fast for 1MB+ strings (walks the string, so faster if there are non-ascii characters early in the string).

!preg_match('/[\\x80-\\xff]/', $input);

ctype_print: 83ms average. Decently fast for 1MB+ strings (walks the string, so faster if there are non-ascii characters early in the string). DO NOTE that this is not really an ascii check.

ctype_print($input);

while/ord: 500ms average. I'm still waiting for the 1MB+ strings test to finish.

function is_ascii($input) {
    $num = 0;
    while( isset( $string[$num] ) ) {
        if( ord( $string[$num] ) & 0x80 ) {
            return false;
        }
        $num++;
    }
    return true;
}
Related