簡體   English   中英

如何檢查字符串中是否至少有一個字母,數字和特殊字符

[英]How to check if string has at least one letter, number and special character in php

我目前正在編寫一個小腳本來檢查每個字符串的內容。

我想知道REGEX將確保字符串有一個字母(上部或下部),一個數字和一個特殊字符?

這是我目前所知的(whcih並不多):

if(preg_match('/^[a-zA-Z0-9]+$/i', $string)):

幫助會很棒!

謝謝!

最簡單(也可能是最好的)方法是使用preg_match進行三次單獨的檢查:

$containsLetter  = preg_match('/[a-zA-Z]/',    $string);
$containsDigit   = preg_match('/\d/',          $string);
$containsSpecial = preg_match('/[^a-zA-Z\d]/', $string);

// $containsAll = $containsLetter && $containsDigit && $containsSpecial

您可以使用正向前瞻來創建單個正則表達式:

$strongPassword = preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$%^&]).*$/');
//                                              special characters  ^^^^

我在這里找到了很好的答案,並解釋了確保給定字符串包含以下每個類別中至少一個字符。

小寫字符,大寫字符,數字,符號

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$

一個簡短的解釋:

^ //字符串的開頭

(?=.*[az]) //使用正向前看以查看是否存在至少一個小寫字母

(?=.*[AZ]) //使用正向前看以查看是否存在至少一個大寫字母

(?=.*\\d) //使用正向前看以查看是否存在至少一個數字

(?=.*[_\\W]) //使用正向前看以查看是否存在至少一個下划線或非單詞字符

.+ //吞噬整個字符串

$ //字符串的結尾

希望對你有所幫助。

最好使用3個不同的正則表達式來執行此操作,因為您需要匹配6種不同的可能性,具體取決於字符串中特殊字符的位置。 但是如果你想在一個正則表達式中進行,並且你的特殊字符是[+?@],那么它是可能的:

$string = "abc@123";
$regex = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$%^&]).*$/"
if (preg_match($regex, $string)) {
   // special characters
}

一個字母是\\pL ,一個數字是\\pN ,一個特殊的字符是[what you want] ,這里我假設它不是一個字母而不是一個數字,所以正則表達式看起來像:

/^(?=.*?\pL)(?=.*?\pN)(?=.*[^\pL\pN])/

假(選擇上面的答案 - 謝謝!)有一個非常簡單的方法來包圍它(如果你不熟悉正則表達式)並想出適合你的東西。

我只想詳細說明一下:

(您可以將其粘貼到http://phptester.net/index.php?lang=en以使用它)

<?php

$pass="abc1A";

$ucl = preg_match('/[A-Z]/', $pass); // Uppercase Letter
$lcl = preg_match('/[a-z]/', $pass); // Lowercase Letter
$dig = preg_match('/\d/', $pass); // Numeral
$nos = preg_match('/\W/', $pass); // Non-alpha/num characters (allows underscore)

if($ucl) {
    echo "Contains upper case!<br>";
}

if($lcl) {
    echo "Contains lower case!<br>";
}

if($dig) {
    echo "Contains a numeral!<br>";
}

// I negated this if you want to dis-allow non-alphas/num:
if(!$nos) {
    echo "Contains no Symbols!<br>"; 
}

if ($ucl && $lcl && $dig && !$nos) { // Negated on $nos here as well
    echo "<br>All Four Pass!!!";
} else {
    echo "<br>Failure...";
}

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM