简体   繁体   English

使用正则表达式

[英]Using regular expressions

What is wrong with this regexp? 这个正则表达式有什么问题? I need it to make $name to be letter-number only. 我需要它才能使$ name成为字母编号。 Now it doens't seem to work at all. 现在它似乎根本没有用。

 if (!preg_match("/^[A-Za-z0-9]$/",$name)) {
  $e[]="name must contain only letters or numbers";
 }

You need a quantifier otherwise it will only allow one character. 你需要一个量词,否则它只允许一个字符。 For example, to require that there must be one or more characters use + : 例如,要求必须有一个或多个字符使用+

/^[A-Za-z0-9]+$/

Your regular expression does only describe one single character. 您的正则表达式仅描述一个单个字符。 Either use a quantifier like + to allow that [A-Za-z0-9] is being repeated one or more times: 使用像+这样的量词允许[A-Za-z0-9]重复一次或多次:

if (!preg_match("/^[A-Za-z0-9]+$/",$name))

Or you can inverse your expression and look for characters that are not alphanumeric ( [^A-Za-z0-9] is the complement of [A-Za-z0-9] ): 或者你可以反转你的表达式并查找不是字母数字的字符( [^A-Za-z0-9][A-Za-z0-9]的补码):

if (preg_match("/[^A-Za-z0-9]/",$name))

Don't forget to look at other functions which will do what you want without the overhead of regexes. 不要忘记查看其他功能,这些功能可以执行您想要的功能,而不会产生正则表达式的开销。 In this case, you could use ctype_alnum . 在这种情况下,您可以使用ctype_alnum

When you don't exactly know what your expression does, sometimes it helps to test it with a tool. 如果您不确切地知道表达式的作用,有时使用工具对其进行测试会有所帮助。 You could try maybe Regex Coach: http://www.weitz.de/regex-coach/ :) 您可以尝试使用Regex Coach: http//www.weitz.de/regex-coach/ :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM