Home  >  Article  >  Backend Development  >  How to replace asterisk in Chinese in php

How to replace asterisk in Chinese in php

藏色散人
藏色散人Original
2021-10-19 09:16:192592browse

php method to replace asterisks with Chinese: 1. Determine whether the characters contain Chinese characters; 2. Use the mb_substr function to replace the specified Chinese part with asterisks.

How to replace asterisk in Chinese in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to replace asterisks in Chinese in php?

PHP user names are processed with asterisks

PHP user names are processed with * signs:

User names: English, Chinese, mixed Chinese and English, Chinese and English The

processing of mixed characters is as follows: the first letter and the end are retained, and the middle is replaced by an * (one character is displayed directly, two characters: Zhang*, three or more characters: Song*Dan)

First determine whether the characters contain Chinese characters, and if so, use the mb_ series of functions (the Chinese here uses UTF-8 format)

UTF-8 Chinese regular: "/[\x{4e00} -\x{9fa5}] /u"

GB2312 Chinese regular: "/[".chr(0xa1)."-".chr(0xff)."] /"

 //判断是否包含中文字符
if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $str)) {
    //按照中文字符计算长度
    $len = mb_strlen($str, 'UTF-8');
    //echo '中文';
    if($len >= 3){
        //三个字符或三个字符以上掐头取尾,中间用*代替
        $str = mb_substr($str, 0, 1, 'UTF-8') . '*' . mb_substr($str, -1, 1, 'UTF-8');
    } elseif($len == 2) {
        //两个字符
        $str = mb_substr($str, 0, 1, 'UTF-8') . '*';
    }
} else {
    //按照英文字串计算长度
    $len = strlen($str);
    //echo 'English';
    if($len >= 3) {
        //三个字符或三个字符以上掐头取尾,中间用*代替
        $str = substr($str, 0, 1) . '*' . substr($str, -1);
    } elseif($len == 2) {
        //两个字符
        $str = substr($str2, 0, 1) . '*';
    }
}

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to replace asterisk in Chinese in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn