深知Regex的威力最近學習一些,偶遇問題,廢話不多說上代碼:
$str = 'Mr.Ck-@139.com';if(preg_match('(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)', $str, $match)) { print_r($match);}$str = '123,456,78,90';if(preg_match('(?[0-9]+)(.(?[0-9]+))*', $str, $match)) { print_r($match);}
錯誤提示:
Warning: preg_match(): Unknown modifier '@' in D:\webServ\index.php on line 15
Warning: preg_match(): Unknown modifier '(' in D:\webServ\index.php on line 23
我不知道是不是因為PHP函數的問題,我相信這個運算式應該是沒問題的,只是preg_match這個函數的什麼機制導致的把?
回複內容:
深知Regex的威力最近學習一些,偶遇問題,廢話不多說上代碼:
$str = 'Mr.Ck-@139.com';if(preg_match('(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)', $str, $match)) { print_r($match);}$str = '123,456,78,90';if(preg_match('(?[0-9]+)(.(?[0-9]+))*', $str, $match)) { print_r($match);}
錯誤提示:
Warning: preg_match(): Unknown modifier '@' in D:\webServ\index.php on line 15
Warning: preg_match(): Unknown modifier '(' in D:\webServ\index.php on line 23
我不知道是不是因為PHP函數的問題,我相信這個運算式應該是沒問題的,只是preg_match這個函數的什麼機制導致的把?
preg_match 的第一個參數為正則的字串, 正則需要開始和結束標記你這裡沒有.
'(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)'(?[0-9]+)(.(?[0-9]+))*
改為
'/(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)/''/(?[0-9]+)(.(?[0-9]+))*/'
- 上面的改了之後還是錯誤的, 錯誤的原因在於:
_-. 中括弧內的 - 線是有特殊含義的(請參考a-z, 0-9).
- 第二個正則中
(? 這樣的寫法是不正確的, PHP 的報錯資訊為:
Warning: preg_match(): Compilation failed: unrecognized character after (? or (?- at offset 2 in T:\1.php on line xx 因為不知道你第二個具體要做啥, 可以直接刪除 ? 號, 或者在 ? 號後面加上 : 號解決報錯的問題.
附改後的代碼:
php[a-zA-Z0-9_\-.]+)@(?:<#host>[a-zA-Z0-9_\-.]+)/', $str, $match)) { print_r($match);}$str = '123,456,78,90';if(preg_match('/([0-9]+)(.([0-9]+))*/', $str, $match)) { print_r($match);}
號碼 最終問題 我解決了