我想檢查字串是否有 16 個字符、包含數字、包含字母并且沒有任何特殊字符。我已經在 javascript 上做過了,但是用戶仍然在作弊,并且有些人在用戶輸入中添加了 < script > 標簽,所以我需要將其轉換為 PHP 以進行服務器端驗證。但我很困惑,我是 PHP 正則運算式的新手,我的代碼有什么問題?如何將所有這些正則運算式組合成一行,因為我對太多的 AND 邏輯運算子感到非常困惑,謝謝:
<?php
function create($referrer=null){
if(strlen($referrer) == 16 and (!empty(preg_match('/\d /g', $referrer))) and (!empty(preg_match('/[a-zA-Z]/g', $referrer)) and empty(preg_match('/[!@#$%^&*()_ \-=\[\]{};\':"\\|,.<>\/?] /', $referrer)))){
echo 'The string has 16 characters, contains digits, contains letters, and does not have any special characters.';
}
}
create("kdsygdbg7j6f5ps2");
?>
uj5u.com熱心網友回復:
您可以為此使用一個正則運算式
但是為了解釋起見,我用下面的例子解釋了它。
一個正則運算式:
var_dump(preg_match('/^[a-zA-Z0-9]{16}$/', 'oaiwejfio12321wejfewiojiowea')); //0, too long
var_dump(preg_match('/^[a-zA-Z0-9]{16}$/', '**(#&($#@')); //0, invalid chars
var_dump(preg_match('/^[a-zA-Z0-9]{16}$/', '1234567891234567')); //1, correct
預匹配
以下資訊有助于了解 preg_match:
preg_match()
pattern如果 匹配給定 ,則 回傳 1 ,如果不匹配,則回傳subject0,或者false失敗。
您對 !empty 的使用
您在代碼中使用 !empty,這使它有點不可讀。preg_match 回傳 1 或 0,因此最好將其與這些值進行比較。但是 !empty 確實可以作業,請看下面的結果:
var_dump(!empty(1)); //true
var_dump(!empty(0)); //false
帶有 preg_match 解釋的正則運算式
1.!empty(preg_match('/\d /g', $referrer))
我已將其替換為以下內容:preg_match('/[0-9]/', $referrer) === 1,因為 g 是未知修飾符。查看ShouldContainDigits底部代碼示例中的類。
2.empty(preg_match('/[a-zA-Z]/g', $referrer))
我已將其替換為以下內容:preg_match('/[a-zA-Z]/', $value) === 1,因為 g 是未知修飾符。查看ShouldContainLetters底部代碼示例中的類。
3.empty(preg_match('/[!@#$%^&*()_ \-=\[\]{};\':"\\|,.<>\/?] /', $referrer))
我已將其替換為以下內容:(preg_match('/[!@#$%^&*()_ \-=\[\]{};\':"\\|,.<>\/?] /', $referrer) === 0). 查看ShouldNotContainSpecialChars底部代碼示例中的類。
完整的代碼示例
我已經重構了這個例子,使每個正則運算式應該做什么更清楚。添加以下代碼test.php并運行php test.php:
<?php
final class Result
{
private $errors = [];
public function __construct() {}
public function withError(string $error) : Result
{
$result = clone $this;
$result->errors[] = $error;
return $result;
}
public function getErrors() : array
{
return $this->errors;
}
public function isValid() : bool
{
return empty($this->errors);
}
}
interface ValidatorStrategy
{
public function isValid(string $value) : bool;
public function getError() : string;
}
final class ShouldBe16CharsInLength implements ValidatorStrategy
{
public function isValid(string $value) : bool
{
return strlen($value) === 16;
}
public function getError() : string
{
return "The string does not have 16 chars";
}
}
final class ShouldContainDigits implements ValidatorStrategy
{
public function isValid(string $value) : bool
{
return preg_match('/[0-9]/', $value) === 1;
}
public function getError() : string
{
return "The string does not contain digits";
}
}
final class ShouldContainLetters implements ValidatorStrategy
{
public function isValid(string $value) : bool
{
return preg_match('/[a-zA-Z]/', $value) === 1;
}
public function getError() : string
{
return "The string does not contain letters";
}
}
final class ShouldNotContainSpecialChars implements ValidatorStrategy
{
public function isValid(string $value) : bool
{
return (preg_match('/[!@#$%^&*()_ \-=\[\]{};\':"\\|,.<>\/?] /', $value) === 0);
}
public function getError() : string
{
return "The string does contain special chars";
}
}
final class Validator
{
private $strategies;
public function __construct(array $strategies)
{
$this->strategies = $strategies;
}
public function validate(string $value) : Result
{
$result = new Result();
foreach($this->strategies as $strategy) {
if(!$strategy->isValid($value)) {
$result = $result->withError($strategy->getError());
}
}
return $result;
}
}
$validator = new Validator([
new ShouldBe16CharsInLength(),
new ShouldContainDigits(),
new ShouldContainLetters(),
new ShouldNotContainSpecialChars()
]);
/**
* Test with string kdsygdbg7j6f5ps2
* array(2) {
["errors"]=>
array(0) {
}
["isValid"]=>
bool(true)
}
*/
$result = $validator->validate("kdsygdbg7j6f5ps2");
var_dump(['errors'=>$result->getErrors(), 'isValid'=>$result->isValid()]);
#
/**
* Test with string &(*&@(
* Result: array(2) {
["errors"]=>
array(4) {
[0]=>
string(33) "The string does not have 16 chars"
[1]=>
string(34) "The string does not contain digits"
[2]=>
string(35) "The string does not contain letters"
[3]=>
string(37) "The string does contain special chars"
}
["isValid"]=>
bool(false)
}
*/
$result = $validator->validate("&(*&@(");
var_dump(['errors'=>$result->getErrors(), 'isValid'=>$result->isValid()]);
你的代碼
我已將您的代碼更改為:
function create($referrer=null){
if(preg_match('/^[a-zA-Z0-9]{16}$/', $referrer) === 1){
echo $referrer . ': The string has 16 characters, contains digits, contains letters, and does not have any special characters.';
}
}
測驗:
create("kdsygdbg7j6f5ps2"); //kdsygdbg7j6f5ps2: The string has 16 characters, contains digits, contains letters, and does not have any special characters.
create("&(*&@("); //... nothing
uj5u.com熱心網友回復:
你可以試試preg_match我做的,它對我有用。
function create($referrer=null){
$uppercase = preg_match('@[A-Z]@', $referrer);
$lowercase = preg_match('@[a-z]@', $referrer);
$number = preg_match('@[0-9]@', $referrer);
if (!$uppercase) {
echo 'Please input atleast one uppercase letter. Try again';
} elseif (!$lowercase) {
echo 'Please input atleast one lower case letter. Try again';
} elseif (!$number) {
echo 'Please input atleast one number. Try again';
} elseif (strlen($newpassword) < 8) {
echo 'Your password must be not less than 8 characters. Try again';
}
}
uj5u.com熱心網友回復:
您正在尋找的 RegEx 正在^[[:alnum:]]{16}$使用:
^字串的開頭[:alnum:]相當于a-zA-Z0-9{16}正好匹配 16 個字符$字串的結尾
這是帶有示例測驗字串的代碼:
<?php
function create($referrer=null){
if((!empty(preg_match('/^[[:alnum:]]{16}$/', $referrer)))){
echo PHP_EOL.'The string '.$referrer .' has 16 characters, contains digits, contains letters, and does not have any special characters.';
}
else{
echo PHP_EOL.'The string '. $referrer .' does not match criteria.';
}
}
$array = [
'a1b2c3D4E5F6G7H8'
,'a1btooshort'
,'a1b2c3D4E5F6G7H8toolong'
,'!@#$%^&*()_ -=['
,']{};\':"\|,.<>/?'
,"a1b2c3D4\nE5F67H8"
];
foreach ($array as $key => $value) {
create($value);
}
現場演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487902.html
標籤:php
上一篇:如何禁用評論審核?
下一篇:如何在PHP中組合多個正則運算式
