2011-11-08 42 views
3

好吧,我正在爲我們的密碼策略編寫一個密碼檢查器,它需要4個主要分類中的3個。我遇到問題的地方是特殊字符匹配。Preg_match所有特殊字符,密碼檢查

這裏是我迄今:

private function PasswordRequirements($ComplexityCount) { 
    $Count = 0; 
    if(preg_match("/\d/", $this->PostedData['password']) > 0) { 
     $Count++; 
    } 
    if(preg_match("/[A-Z]/", $this->PostedData['password']) > 0) { 
     $Count++; 
    } 
    if(preg_match("/[a-z]/", $this->PostedData['password']) > 0) { 
     $Count++; 
    } 
    // This is where I need help 
    if(preg_match("/[~`[email protected]#$%^&*()_-+=\[\]{}\|\\:;\"\'<,>.]/", $this->PostedData['password']) > 0) { 
     $Count++; 
    } 

    if($Count >= $ComplexityCount) { 
     return true; 
    } else { 
     return false; 
    } 
} 

所以基本上我在做什麼是檢查每個字母,數字,大寫字母,小寫字母和特殊字符的字符串。我們對任何特殊字符沒有任何限制,我也需要unicode字符。 \ W在這種情況下工作還是會再次包含數字?我在\ W上找不到很棒的文檔,所以我不清楚這一部分。

有誰知道一個簡單的正則表達式,可以涵蓋所有不包含數字和字母的特殊字符和unicode字符嗎?

任何人都可以自由使用這個,因爲我認爲超過一些人一直在尋找這個。

+0

這是一個很好的網頁,可以解釋您的一些猜測:http://www.regular-expressions.info/reference.html – Marcus

回答

12

這種模式可以允許所有不是數字或a-Z的字符。

[^\da-zA-Z] 

關於\W這是一個否定\w,這是一樣的[A-Za-z0-9_]。因此\W是不是英文字母,數字或下劃線的所有字符。

正如我爲學習正則表達式提到的this is a great resource。這裏有一個很好的網站test the regex

+0

我正在拍腦袋。非常感謝你,我甚至沒有想過要做與以前的檢查相反的事情。並感謝您將會派上用場的資源。 - 傑夫 – Jeff

+0

並感謝您的快速響應 – Jeff

2

您可以使用POSIX字符類[[:punct:]]的 '特殊' 字符:

<?php 
$regex = '[[:punct:]]'; 

if (preg_match('/'.$regex.'/', 'somepas$', $matches)) { 
    print_r($matches); 
} 
?> 

給出:

Array 
(
    [0] => $ 
) 
7

如果你想匹配的特殊字符

preg_match('/[\'\/~`\[email protected]#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $input)