MENU

php 正则匹配中文中括号和英文中括号 解决正则匹配中文乱码的问题

December 21, 2019 • 已被 175 位童鞋围观过 • 代码分享

下午的时候 写代码 发现正则匹配中文字符串的时候,会出现乱码,上网查了很久也不知道是什么原因,很蛋疼。
不过好在测试了很久之后,找到解决的方法 那就是先把字符串转为unicode,匹配了之后再转回来,完美解决乱码问题。话不多说,上代码。

function Regex_Str($str){
    $sms="u".unicode_encode($sms, 'UTF-8', "\\u", '');
    //匹配 【】[] 「」三个格式
    $strPattern = "/(?<=(?:\\u4144))((?!\\u4400).)*(?=(?:\\u4400))|(?<=\\u23296)((?!\\u23808).)*(?=\\u23808)|(?<=\\\u3120)((?!\\u3376).)*(?=\\u3376)/";
    preg_match_all($strPattern,$str,$strs);
    //print_r($strs);
    return unicode_decode($froms[0][0], 'UTF-8', "\\u", '');
}

/**
 * $str 原始中文字符串
 * $encoding 原始字符串的编码,默认GBK
 * $prefix 编码后的前缀,默认"&#"
 * $postfix 编码后的后缀,默认";"
 */
function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $str = iconv($encoding, 'UCS-2', $str);
    $arrstr = str_split($str, 2);
    $unistr = '';
    for($i = 0, $len = count($arrstr); $i < $len; $i++) {
        $dec = hexdec(bin2hex($arrstr[$i]));
        $unistr .= $prefix . $dec . $postfix;
    } 
    return $unistr;
} 

/**
 * $str Unicode编码后的字符串
 * $decoding 原始字符串的编码,默认GBK
 * $prefix 编码字符串的前缀,默认"&#"
 * $postfix 编码字符串的后缀,默认";"
 */
function unicode_decode($unistr, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $arruni = explode($prefix, $unistr);
    $unistr = '';
    for($i = 1, $len = count($arruni); $i < $len; $i++) {
        if (strlen($postfix) > 0) {
            $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
        } 
        $temp = intval($arruni[$i]);
        $unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
    } 
    return iconv('UCS-2', $encoding, $unistr);
}
Last Modified: September 28, 2023