php正則表達匹配中文若干問題的解決方案

來源:互聯網
上載者:User
  1. $str = '中華人民共和國123456789abcdefg';
  2. echo preg_match("/^[u4e00-u9fa5_a-zA-Z0-9]{3,15}$",$strName);
  3. ?>
複製代碼

運行以上代碼,會提示:Warning: preg_match(): Compilation failed: PCRE does not support L, l, N, P, p, U, u, or X at offset 3 in F:wwwrootphptest.php on line 2

原因在於:PHPRegex中不支援下列 Perl 逸出序列:L, l, N, P, p, U, u, or X

在 UTF-8 模式下,允許用“x{...}”,花括弧中的內容是表示十六進位數位字串。

原來的十六進位逸出序列 xhh 如果其值大於 127 的話則匹配了一個雙位元組 UTF-8 字元。解決方案:

  1. preg_match("/^[x80-xff_a-zA-Z0-9]{3,15}$",$strName);
  2. preg_match('/[x{2460}-x{2468}]/u', $str);
複製代碼

匹配 內碼漢字按照他提供的方式進行測試:

  1. $str = "php編程";
  2. if (preg_match("/^[x{2460}-x{2468}]+$/u",$str)) {
  3. print("該字串全部是中文");
  4. } else {
  5. print("該字串不全部是中文");
  6. }
  7. ?>
複製代碼

這樣操作,依然對是否為中文判斷失常。不過,既然x表示的十六進位資料,為什麼和js裡邊提供的範圍x4e00-x9fa5不一樣呢?於是將代碼修改為如下內容:

  1. $str = "php編程";
  2. if (preg_match("/^[x4e00-x9fa5]+$/u",$str)) {
  3. print("該字串全部是中文");
  4. } else {
  5. print("該字串不全部是中文");
  6. }
  7. ?>
複製代碼

warning又一次產生了:Warning: preg_match() [function.preg-match]: Compilation failed: invalid UTF-8 string at offset 6 in test.php on line 3接著修改,給“4e00”和“9fa5”兩邊分別用"{"和“}”包起來,跑了一遍,發現這次準確了:

  1. $str = "php編程";
  2. if (preg_match("/^[x{4e00}-x{9fa5}]+$/u",$str)) {
  3. print("該字串全部是中文");
  4. } else {
  5. print("該字串不全部是中文");
  6. }
  7. ?>
複製代碼

知道了php中utf-8編碼下用Regex匹配漢字的最終正確運算式:/^[x{4e00}-x{9fa5}]+$/u,

最終版的實現代碼:

  1. //if (preg_match(“/^[".chr(0xa1)."-".chr(0xff)."]+$/”, $str)) { //只能在GB2312情況下使用
  2. if (preg_match(“/^[x7f-xff]+$/”, $str)) { //相容gb2312,utf-8
  3. echo “正確輸入”;
  4. } else {
  5. echo “錯誤輸入”;
  6. }
  7. ?>
複製代碼

例2,

  1. $action = trim($_GET['action']);
  2. if($action == "sub")
  3. {
  4. $str = $_POST['dir'];
  5. //if(!preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/",$str)) //GB2312漢字字母數字底線Regex
  6. if(!preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u",$str)) //UTF-8漢字字母數字底線Regex
  7. {
  8. echo"您輸入的[".$str."]含有違法字元";
  9. }
  10. else
  11. {
  12. echo "您輸入的[".$str."]完全合法,通過!";
  13. }
  14. }
  15. ?>
複製代碼

附,php中雙位元組字元編碼範圍

1. GBK (GB2312/GB18030)

x00-xff GBK雙位元組編碼範圍x20-x7f ASCIIxa1-xff 中文 gb2312x80-xff 中文 gbk

2. UTF-8 (Unicode)

u4e00-u9fa5 (中文)x3130-x318F (韓文xAC00-xD7A3 (韓文)u0800-u4e00 (日文)

就介紹這些吧,希望有助於大家理解php正則匹配中文的方法。程式員之家,祝大家學習進步。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.