Home >Backend Development >PHP Problem >How to exclude Chinese characters in php (three methods)
Chinese characters are a common problem during website development. In PHP, text processing functions, such as preg_replace, str_replace, etc., can process Chinese characters normally. However, in some specific scenarios, we need to exclude Chinese characters. For example, if a username field is only allowed to contain English letters and numbers, we need to exclude Chinese characters.
This article will introduce several methods of excluding Chinese characters in PHP for readers' reference.
Method 1: Use regular expressions
Using regular expressions can more easily exclude Chinese characters. The following is a sample code:
function excludeChinese($str) { return preg_replace("/[\x7f-\xff]+/", '', $str); } $name = "张三"; $name = excludeChinese($name); echo $name; //输出为空
In the above code, the preg_replace function is used to replace the Chinese characters in the string with an empty string to exclude Chinese characters. [\x7f-\xff] means matching all Chinese characters in the ASCII code table.
Considering that the encoding of Chinese characters is not unique, this method is not perfect. In some cases, other methods of Chinese character exclusion may be necessary.
Method 2: Use the mb_check_encoding function
Use the mb_check_encoding function to exclude Chinese characters. The following is a sample code:
function excludeChinese($str) { $len = mb_strlen($str); for ($i=0; $i<$len; $i++) { $char = mb_substr($str, $i, 1); if (!mb_check_encoding($char, 'ASCII')) { return ''; } } return $str; } $name = "张三"; $name = excludeChinese($name); echo $name; //输出为空
The above code uses the mb_check_encoding function to detect whether each character in the string is an ASCII character. If not, an empty string is returned to exclude Chinese characters.
Method 3: Using the iconv function
Another way to exclude Chinese characters is to use the iconv function. The following is a sample code:
function excludeChinese($str) { $str = iconv("UTF-8", "ASCII//IGNORE", $str); return $str; } $name = "张三"; $name = excludeChinese($name); echo $name; //输出空字符串
In the above code, the encoding of the string is first converted from UTF-8 to ASCII encoding, then the Chinese characters are ignored through the IGNORE parameter, and finally the result string is returned.
Conclusion
The above methods can all achieve the exclusion of Chinese characters, and the specific method can be selected according to needs. Of course, different methods may be needed in different scenarios. In actual development, it is best to make a choice based on specific application conditions.
The above is the detailed content of How to exclude Chinese characters in php (three methods). For more information, please follow other related articles on the PHP Chinese website!