2016-11-20 265 views
-1

我的字符串PHP,Regex;只允許數字,字母和空格

  • 可能只包含數字,字母和空格,僅此而已
  • 必須至少包含ZWO字母
  • 必須至少包含十位數

如果我的字符串與此模式不匹配,如何回顯某些內容?

我希望任何正則表達式的專家都可以幫助我,因爲我對它不是很有經驗。

編輯:

這是我試過至今:

if (preg_match('/^[A-Z]+[0-9]+/', $myString)) { 
    echo "Error!"; 
} 
+0

我們在這裏不是做你的工作你。你試過什麼了? – Chris

+0

@Chris我更新了我的問題。 – user7128548

+0

我經常喜歡問,讓查詢者認爲,而不是隻是在這種情況下得到答案,但在這裏的版主不歡迎這樣:)無論如何,我會嘗試現在:)看,你的正則表達式'/^[AZ] + [az ] + [0-9] + /'表示字符串在開始時必須有一些大寫字母,然後是一些小寫字母,然後是一些數字。所以「Qwerty10」會匹配,但「Qwerty10」不會,「10Querty」也不會,現在輪到你了:) – AlexandrX

回答

0

這將做的工作:

/^(?=(?:.*[a-z]){2})(?=(?:.*\d){10})[a-z0-9 ]+$/i 

在PHP中使用它:

if (preg_match('/^(?=(?:.*[a-z]){2})(?=(?:.*\d){10})[a-z0-9 ]+$/i', $myString)) { 
    echo "OK!\n"; 
} else { 
    echo "Error!\n"; 
} 

說明:

/    : regex delimiter 
^   : start of string 
    (?=   : lookahead 
    (?:   : non capture group 
     .*[a-z] : 0 or more any character followed by a letter 
    ){2}  : end of group, must be present twice 
)    : end of lookahead 
    (?=   : lookahaed 
    (?:   : non capture group 
     .*\d  : 0 or more any character followed by a digit 
    ){10}  : end of group, must be present 10 times 
)    : end of lookahaed 
    [a-z0-9 ]+ : character class, allowed characters are letters, digit and space 
    $    : end of string 
/i    : regex delimiter, case insensitive 

你在向前here找到有用的信息,對組here

相關問題