4

What is wrong with this regexp? I need it to make $name to be letter-number only. 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";
 }
0

4 Answers 4

9

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]+$/
Sign up to request clarification or add additional context in comments.

Comments

2

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:

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]):

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

Comments

2

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.

Comments

1

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/ :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.