<?php
$str = '中華人民共和國123456789abcdefg';
echo preg_match("/^[\u4e00-\u9fa5_a-zA-Z0-9]{3,15}/", $str);
// Warning: Compilation failed: PCRE does not support \u at offset 3
?>
PHP PCRE 引擎不支援 Perl 風格的 \uXXXX、\U、\L、\X 等轉義序列。
<?php
// 方案一:Unicode 碼點範圍(需 u 修飾符)
$pattern = '/^[\x{4e00}-\x{9fa5}_a-zA-Z0-9]{3,15}/u';
// 方案二:UTF-8 位元組範圍(不需 u 修飾符,相容性佳)
$pattern = '/^[\x80-\xff_a-zA-Z0-9]{3,15}/';
$str = '中華人民共和國123456789abcdefg';
var_dump(preg_match($pattern, $str)); // int(1)
?>
| 寫法 | 修飾符 | 匹配對象 | 適用場景 |
|---|---|---|---|
[\u4e00-\u9fa5] | 不支援 | - | 錯誤寫法 |
[\x{4e00}-\x{9fa5}] | u (UTF-8) | Unicode 碼點 | 精確匹配特定字符集 |
[\x80-\xff] | 無 | UTF-8 多位元組首位元組 | 快速匹配所有非 ASCII 字元 |
/^[\x{4e00}-\x{9fa5}]+$/u/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_]+$/u/^[\x80-\xff_a-zA-Z0-9_]+$/u 修飾符,否則 PCRE 會以位元組模式解析導致錯誤