Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regular expressions

Tags:

regex

php

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";
 }
like image 952
Tom Avatar asked Dec 09 '22 15:12

Tom


2 Answers

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]+$/
like image 200
Mark Byers Avatar answered Dec 12 '22 05:12

Mark Byers


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))
like image 40
Gumbo Avatar answered Dec 12 '22 03:12

Gumbo