Recently published

Practice notes

Home arrow Blog arrow Checking for non-ASCII codes

Checking for non-ASCII codes

I wanted a simple PHP routine for detecting non-ASCII codes in strings. They are the ones that need some kind of special treatment to appear on web sites. Maybe they can be processed as UTF-8 or maybe they are best turned into HTML elements. On the web, I found a routine for removing non-ASCII characters by a guy called Vivek:

function removeNonAscii($string) {
   return preg_replace('/[^x00-x7f]/','',$string);
} 

Well, that gives the logic required, so we can detect non-ASCII with a rather similar function:

function containsNonAscii($string) {
    return $string == preg_replace('/[^x00-x7f]/','',$string) ? false : true;
} 

#128006 • 03/26/2009 9:50pm by Martin Brampton • Vote: Up votes (912) Down votes (534)

blog comments powered by Disqus