-1

I have this email regex, and i would like to make same thing with a name regex, so you can't write numbers in a name, how should i change it?

if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
    $emailError = 'You entered an invalid email address.';
    $hasError = true;
}

I know that [a-z0-9_.-] means that a-z 0-9 and _ . - is usable. But i want to only use a-z and this is why my brain is breaking across, as i don't understand the whole sentence, could anyone "translate" it to only use a-z and no numbers neither _ - .? I would like it to be changed to a name regex, so people can't write numbers in their name.

I understand that i can write

if (!preg_match("/^[[:alnum:]][a-z]*@[a-z]+\.[a-z]{2,4}$/i", trim($_POST['name']))) {
    $nameError = 'You entered invalid characters in your name.';
    $hasError = true;
}

but for me it doesn't make any sense, how i should enter that into the regex above.

but i could also type in this? so i say if it contains 0-9 then its invalid? but i don't know what it means all these characters in the sentence.

if (preg_match("/^[[:alnum:]][0-9]*@[0-9]+\.[0-9]{2,4}$/i", trim($_POST['name']))) {
    $nameError = 'You entered invalid characters in your name.';
    $hasError = true;
}


I tried to research about "preg_match" but i can't find an explanation, so i can make my a regex for "preg_match" on my own

Zeuthenjr
  • 107
  • 2
  • 11
  • 2
    "Only alphanumeric and no numbers"? You know alphanumeric includes numbers, right? (Also, consider that people may have spaces, apostrophes, accented characters, hyphens, and perhaps other things I haven't thought of in their name...) – Matt Gibson Dec 13 '14 at 15:09
  • this question is not a duplicate of the one you linked. – Avinash Raj Dec 14 '14 at 07:06

2 Answers2

1

You could try the below.

/^[a-z]+@[a-z]+\.[a-z]{2,4}$/i
  • [[:alnum:]] Matches both alphabets and numbers but POSIX [[:alpha:]] matches only the alphabets.
  • [a-z]* zero or more lowercase letters. [a-z]+ one or more lowercase letters.
  • i modifier helps to do a case insensitive match.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

If you want to understand the regex pattern try using http://regex101.com . That will let you analyze each part of the pattern.

You can try using this, it should do the job:

/^[[:alpha:]][a-z]*@[a-z]+\.[a-z]{2,4}$/i

But the simpler regex for a name check that I use and haven't had any issues with is:

/^([a-z])+$/i

Although the first one may be better (?) the second one makes the regex slightly more understandable in my opinion.

Myles Offord
  • 34
  • 2
  • 5