中文正則匹配模式取決於檔案/字串編碼:
| 編碼 | 範圍 | 正則模式 | 修飾符 |
|---|---|---|---|
| GBK/GB2312 | 漢字區 | [\x80-\xff]+ 或 [\xa1-\xff]+ | 無 |
| UTF-8 | 基本漢字 | [\x{4e00}-\x{9fa5}]+ | /u (PCRE_UTF8) |
| UTF-8 | 擴展區 | [\x{4e00}-\x{9fff}]+ | /u |
<?php
$str = '學習 PHP 是一件快樂的事。Hello World!';
preg_match_all('/[\x{4e00}-\x{9fa5}]+/u', $str, $matches);
print_r($matches[0]);
/*
Array
(
[0] => 學習
[1] => 是一件快樂的事
)
*/
?>
function isPureChinese($str): bool {
return (bool)preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $str);
}
var_dump(isPureChinese('測試字串')); // true
var_dump(isPureChinese('Test123')); // false
var_dump(isPureChinese('測試123')); // false
function hasChinese($str): bool {
return (bool)preg_match('/[\x{4e00}-\x{9fa5}]/u', $str);
}
<?php
// 檔案儲存為 GBK 編碼
$str = '中文測試';
if (preg_match('/^[\x80-\xff]+$/', $str)) {
echo '全是中文';
} else {
echo '包含非中文';
}
// 更精確的 GB2312 範圍
if (preg_match('/^[\xb0-\xf7][\xa0-\xfe]+$/', $str)) {
echo '符合 GB2312 漢字編碼規範';
}
function validateChineseName($name): bool {
return (bool)preg_match('/^[\x{4e00}-\x{9fa5}]{2,10}$/u', $name);
}
$filtered = preg_replace('/[\x{4e00}-\x{9fa5}]/u', '', $input); // 移除中文
$onlyChinese = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $input); // 只保留中文
$str = 'PHP中文網';
preg_match_all('/([\x{4e00}-\x{9fa5}]+|[a-zA-Z0-9]+)/u', $str, $m);
print_r($m[0]); // ['PHP', '中文網']
mb_ereg()、mb_strlen() 等原生支援多位元組preg_match() 配合 /u 修飾符通常效能足夠intl 擴展的 BreakIterator/u 修飾符,否則按單位元組匹配導致錯誤\x{4e00}-\x{9fa5} 涵蓋常用漢字,罕見字可能在擴展區. 匹配中文(單位元組模式下匹配半個字元)