本文介绍了PHP - preg_match()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我希望用户能够输入 A-Z 中的每个字符和 0-9 中的每个数字,但我不希望他们输入特殊字符".

Alright, so I want the user to be able to enter every character from A-Z and every number from 0-9, but I don't want them entering "special characters".

代码:

if (preg_match("/^[a-zA-Z0-9]$/", $user_name)) {
    #Stuff
}

它如何检查给定的所有字符,然后检查它们是否匹配?我已经尝试过 preg_match_all(),但老实说我并没有真正理解它.

How is it possible for it to check all of the characters given, and then check if those were matched? I've tried preg_match_all(), but I didn't honestly understand much of it.

就像用户输入FaiL65Mal"一样,我希望它允许并继续.但是如果他们输入Fail{]^7(,",我希望它出现错误.

Like if a user entered "FaiL65Mal", I want it to allow it and move on. But if they enter "Fail{]^7(,", I want it to appear with an error.

推荐答案

您只需要在正则表达式中添加一个量词:

You just need a quantifier in your regex:

零个或多个字符*:

/^[a-zA-Z0-9]*$/

一个或多个字符+:

/^[a-zA-Z0-9]+$/

您的正则表达式只会匹配一个字符串,它只包含一个字母或数字字符.您需要上述零个或多个或一个或多个选项之一,具体取决于您是要允许还是拒绝空字符串.

Your regex as is will only match a string with exactly one character that is either a letter or number. You want one of the above options for zero or more or one or more, depending on if you want to allow or reject the empty string.

这篇关于PHP - preg_match()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:15