2011-04-05 284 views
8

我不想preg_match_all ......因爲表單字段只允許數字和字母......只是不知道正確的語法是什麼...PHP的preg_match的數字和字母,無特殊字符

沒有什麼奇特的......只需要知道只查找數字和字母的preg_match語句的正確語法。像

preg_match('/^([^.]+)\.([^.]+)\.com$/', $unit) 

但是,這東西看起來不換號太....

+3

什麼是你的問題? – 2011-04-05 14:16:53

+1

請更精確地說,你想要做什麼。 – 2011-04-05 14:17:18

+0

你可以提供更多關於你想要在這裏實現的細節嗎?也許是一個例子。你想匹配所有的alphanum還是第一個,還是其他的? – whoughton 2011-04-05 14:17:33

回答

25

如果你只是想確保字符串只包含字母數字字符。 A-Z,a-z,0-9你不需要使用正則表達式。

使用ctype_alnum()

從文檔實例:

<?php 
$strings = array('AbCd1zyZ9', 'foo!#$bar'); 
foreach ($strings as $testcase) { 
    if (ctype_alnum($testcase)) { 
     echo "The string $testcase consists of all letters or digits.\n"; 
    } else { 
     echo "The string $testcase does not consist of all letters or digits.\n"; 
    } 
} 
?> 

上面的例子將輸出:

The string AbCd1zyZ9 consists of all letters or digits. 
The string foo!#$bar does not consist of all letters or digits. 
+3

我不知道'ctype_alnum'。 +1 – 2011-04-05 14:21:21

2

如果你想匹配大於1,那麼你需要,但爲我們提供了一些代碼,我們可以幫助更好。

雖然,在此期間:

preg_match("/([a-zA-Z0-9])/", $formContent, $result); 
print_r($result); 

:)

10
if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){ 

} else { 

} 
+4

它不會讓我編輯它,因爲它沒有足夠的字符,但(「/(A-Za-z0-9)+ /」,$ content)應該是(「/ [A-Za-z0-9 ] + /「,$ content)。注意[而不是( – emilyk 2013-04-03 17:54:42

+1

@emilyk嘗試了兩次來處理編輯來解決這個問題,但每次都被拒絕,所以我們會堅持不工作的版本。 – bicycle 2013-06-10 08:54:23