Check If Preg Match False instead of True

风流意气都作罢 提交于 2019-12-03 13:00:21

问题


I have this code that makes sure the username is only letters and numbers but then way my code is set up I need it to check if the preg_match is false. Right now it says "if secure echo this" I need it's logic to say "if not secure say this". Can someone help me out?

if (preg_match('/[A-Z]+[a-z]+[0-9]+/', $username))
{
    echo 'Secure enough';
}

回答1:


You can negate the condition like this:

if (!preg_match('/^[A-Za-z0-9]+$/', $username))
{
    echo 'Secure enough';
}

Also, your regex needs to be [A-Za-z0-9]+ if you mean "alphanumeric" (only letters and numbers) as a whole.

The regex in your code would match if the username 1) starts with a capital letter (or more than one) 2) is followed by one or more lower-case letter and 3) ends with one or more number(s).

Edit:

I'm really not sure if this is what you want. You can do, basically:

if (preg_match('/^[A-Za-z0-9]+$/', $username)) {
    echo 'Is only letters and numbers';
} else {
    echo 'Contains some other characters';
}

Do you want to make sure the string contains special characters so that it will be "secure enough"? Or do you want to make sure that it does not contains special characters, so there won't be any problems processing special characters at some point?

A secure password would be one with special characters and while you probably don't want to enforce this (depending on your target audience), you'd usually want your system to support special characters in passwords.




回答2:


That's what the ! operator is for, so just say

if (!preg_match.....)

or of course this is what the else clause is for, either way this is rudimentary programming and you need to read a basic tutorial before asking such simple things.



来源:https://stackoverflow.com/questions/18925104/check-if-preg-match-false-instead-of-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!