PHP – How To Check Whether or Not a String Contains non-ASCII chars

In this post shows you two approaches how to check if a string contains non-ASCII chars or not using PHP.

1. Using mb_detect_encoding()

The code below shows you how to do this using the built-in PHP function mb_detect_encoding() approach.

example1.php
function containsNonAsciiChar($string) {
    return !mb_detect_encoding($string, 'ASCII', true);
}

 

2. Using regular expression

The code below shows you how to do this using the regular expression approach.

example2.php
function containsNonAsciiChar($string) {
    return preg_match('/[^\x20-\x7f]/', $string);
}