Check If Preg Match False instead of True

久未见 提交于 2019-12-03 03:57:30

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.

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.

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