开发者

Regex not working for password? not sure why

开发者 https://www.devze.com 2023-02-28 05:01 出处:网络
So I have a regex code to make sure the password is from 4 to 13 characters, it keeps failing public function valid_password($password){

So I have a regex code to make sure the password is from 4 to 13 characters, it keeps failing

public function valid_password($password){
        if(preg_match('^.{3,14}^', $password)){
            return true;
        }//end if
        else{
            ret开发者_StackOverflowurn false;
        }//end else     
    } 

I'm using regex and not php's length attribute because I will be adding more regex code later on. However, now I'm stuck with this failing program.

The problem is, it makes sure the password is over 3 characters however it doesn't care how long it is as if I have set no limit.

Thanks in advance


You have used ^ as delimiters php.net/mregexp.reference.delimiters.php here:

^.{3,14}^

That's possible, but not a good idea in your case, because you need the ^ for its actual purpose. It matches the start of the subject normally. And to correctly count the length, yout need to do that. You also need the $ end of subject meta character.

So basically:

preg_match('/^.{3,14}$/'

Now if you want to combine this regex with other match criteria, I would recommend this fancy assertion syntax:

preg_match('/(?=^.{3,14}$) (...)/x', $password)

This will allow you to specify something else in place of ... - and keep the length check implicit.


^ is the anchor for the beginning of a string. The end of a string is delimited using $:

public function valid_password($password) {
    return preg_match('~^.{3,14}$~', $password);
}

But in this case I wouldn't use a regex, but the strlen function instead:

public function valid_password($password) {
    $length = strlen($password);
    return $length >= 3 && $length <= 14;
}

If you like hacking around to save you that line:

public function valid_password($password) {
    return isset($password[2]) && !isset($password[14]);
}

But really, why do you want to restrict password length to 14 characters? That way you prevent people from choosing really secure passwords. You probably should raise that limit.


Try this:

preg_match('/^.{3,14}$/', $password)


try

preg_match('/^.{3,14}$/', $password)

but regexp for counting string length?? = Overkill


^ matches the start of a string, not the end. $ matches the end.

And you forgot your delimiters.

The full, fixed line is:

if (preg_match('/^.{3,14}$/', $password)) {

However, I strongly recommend that you instead use:

$len = strlen($password);
if ($len >= 3 && $len <= 14) {

instead, since regular expressions are completely overkill for this.

0

精彩评论

暂无评论...
验证码 换一张
取 消