php
  • regex
  • preg-match
  • 2012-08-08 151 views 1 likes 
    1

    我想測試一個字符串,看看它是否包含除字母數字或標點符號以外的字符,如果是,請設置錯誤。我有下面的代碼,但它似乎沒有工作,因爲它讓「CZW205é」通過。在正則表達式中我毫無希望,似乎無法解決問題。正則表達式來匹配標點符號和字母數字字符

    if(!preg_match("/^[a-zA-Z0-9\s\p{P}]/", $product_id)) { 
        $errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes'; 
        continue; 
    } 
    

    在此先感謝您的幫助。

    回答

    8

    你可以做

    if(preg_match("/[^a-zA-Z0-9\s\p{P}]/", $product_id)) { 
        $errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes'; 
        continue; 
    } 
    

    [^...]是否定字符類,只要發現不在類內的東西,它就會匹配。

    (而且爲此我刪除了preg_match()前的否定)

    +0

    非常感謝。對不起,花了這麼長時間來回復,但我仍然得到錯誤500s,所以我測試了什麼是錯的,我完全相信你的方法正在工作。並感謝所有其他解決方案提供商! – PaulSkinner 2012-08-08 11:48:15

    1
    /^[a-zA-Z0-9\s\p{P}]+$/ 
    

    不要忘記標記字符串的結束與$

    1

    那是因爲你只匹配第一個字符,試試這個代碼:

    if(preg_match("/[^\w\s\p{P}]/", $product_id)) { 
        $errors[$i] = 'Please only enter alpha-numeric characters, dashes, underscores, colons, full-stops, apostrophes, brackets, commas and forward slashes'; 
        continue; 
    } 
    

    注:\w是速記[a-zA-Z0-9_]

    +0

    '\ w'還包括'\ D'和下劃線'_' – Toto 2012-08-08 11:55:13

    +0

    是感謝我忘了:) – Oussama 2012-08-08 11:59:35

    相關問題