php 检查 Preg 是否匹配 False 而不是 True

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18925104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:29:26  来源:igfitidea点击:

Check If Preg Match False instead of True

phppreg-matchusername

提问by user2362601

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?

我有这段代码可以确保用户名只是字母和数字,但是我的代码设置方式我需要它来检查 preg_match 是否为假。现在它说“如果安全回应这个”我需要它的逻辑说“如果不安全说这个”。有人可以帮我吗?

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

回答by tmh

You can negate the condition like this:

您可以像这样否定条件:

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

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

此外,[A-Za-z0-9]+如果您的意思是“字母数字”(仅字母和数字)作为一个整体,则您的正则表达式需要是。

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).

如果用户名 1) 以大写字母(或多个)开头 2) 后跟一个或多个小写字母 3) 以一个或多个数字结尾,则代码中的正则表达式将匹配。

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 notcontains 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.

安全密码是带有特殊字符的密码,虽然您可能不想强制执行此操作(取决于您的目标受众),但您通常希望系统支持密码中的特殊字符。

回答by TravisO

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.

或者当然这就是 else 子句的用途,无论哪种方式,这都是基本的编程,在问这样简单的事情之前,您需要阅读基本教程。