PHP 正則提取多語言文字需理解 Unicode 區塊與 PCRE 修飾符。本文系統整理中日韓 (CJK) 字符 Unicode 範圍,解決 /[\u4e00-\u9fa5]/ 在 PHP 中報錯的問題,提供生產可用的提取函數。
| 語言 | Unicode 範圍 | 說明 |
|---|---|---|
| 中文 (CJK 統一表意文字) | U+4E00 - U+9FFF | 常用漢字 20,992 字 |
| 中文擴展 A | U+3400 - U+4DBF | 罕用字 |
| 中文擴展 B | U+20000 - U+2A6DF | 超大字符集,需 UTF-32 或 surrogate pair |
| 韓文諺文音節 | U+AC00 - U+D7AF | 11,172 個組合音節 |
| 韓文字母 | U+1100 - U+11FF | 組合字母 |
| 韓文兼容字母 | U+3130 - U+318F | 單獨字母 |
| 日文平假名 | U+3040 - U+309F | |
| 日文片假名 | U+30A0 - U+30FF | |
| 日文漢字 | U+4E00 - U+9FFF | 與中文共用區塊 |
\x{XXXX}(大括號),而非 \uXXXX(JavaScript 風格)。[\x{4e00}-\x{9fff}]。<?php
class TextExtractor {
/** 提取中文 */
public static function chinese($text) {
return self::extract($text, '\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}');
}
/** 提取日文 (含假名、漢字) */
public static function japanese($text) {
return self::extract($text, '\x{3040}-\x{309f}\x{30a0}-\x{30ff}\x{4e00}-\x{9fff}');
}
/** 提取韓文 */
public static function korean($text) {
return self::extract($text, '\x{ac00}-\x{d7af}\x{1100}-\x{11ff}\x{3130}-\x{318f}');
}
/** 通用提取 */
private static function extract($text, $unicodeRanges) {
$pattern = '/[' . $unicodeRanges . ']+/u'; // 關鍵:u 修飾符
preg_match_all($pattern, $text, $matches);
return $matches[0] ?? [];
}
}
// 測試
$text = "Hello 世界 안녕하세요 こんにちは 123";
print_r(TextExtractor::chinese($text)); // ["世界"]
print_r(TextExtractor::japanese($text)); // ["こんにちは"]
print_r(TextExtractor::korean($text)); // ["안녕하세요"]
<?php
// ❌ 錯誤:PHP 不支援 \uXXXX
preg_match_all('/[\u4e00-\u9fa5]+/', $text, $m);
// Warning: Compilation failed: PCRE does not support \u...
// ✅ 正確:使用 \x{XXXX}
preg_match_all('/[\x{4e00}-\x{9fa5}]+/u', $text, $m);
// ❌ 錯誤:忘記 u 修飾符
preg_match_all('/[\x{4e00}-\x{9fa5}]+/', $text, $m);
// 會將每個 UTF-8 字節單獨匹配,產生亂碼結果
// ✅ 完整模式:提取所有 CJK 文字(含擴展)
$cjkPattern = '/[\x{2e80}-\x{2eff}\x{2f00}-\x{2fdf}\x{3040}-\x{309f}\x{30a0}-\x{30ff}\x{3100}-\x{312f}\x{3130}-\x{318f}\x{3190}-\x{319f}\x{31a0}-\x{31bf}\x{31c0}-\x{31ef}\x{31f0}-\x{31ff}\x{3200}-\x{32ff}\x{3300}-\x{33ff}\x{3400}-\x{4dbf}\x{4e00}-\x{9fff}\x{ac00}-\x{d7af}\x{f900}-\x{faff}\x{fe30}-\x{fe4f}\x{ff00}-\x{ffef}]+/u';
?>
<?php
function cleanAndExtract($rawText) {
// 1. 移除控制字元
$text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $rawText);
// 2. 統一空白
$text = preg_replace('/\s+/u', ' ', $text);
// 3. 提取目標語言
$chinese = TextExtractor::chinese($text);
$english = preg_split('/[\x{4e00}-\x{9fff}]+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
return [
'chinese' => $chinese,
'english' => array_map('trim', $english),
'mixed' => $text
];
}
?>
mb_ereg 系列或 intl 擴展的 Normalizer、BreakIterator。static $re = null; if (!$re) $re = '/.../u';。preg_match_all 一次性提取。