3

I have looked all around here and online for a solution to this.

The problem is I only want to acceppt letters only. However, if I enter as least one letter, no matter if there are symbols or numbers, then it'll take it. How do I get only letters?

if (!preg_match("/[a-zA-Z]/", $_POST["firstname"]))
    $error = "<br />PLease enter a valid first name";
Nordehinu
  • 338
  • 1
  • 3
  • 11
Anthony
  • 69
  • 1
  • 5
  • possible duplicate of [How can I check a form POST only contains letters on multiple fields using preg\_match?](http://stackoverflow.com/questions/7828684/how-can-i-check-a-form-post-only-contains-letters-on-multiple-fields-using-preg) – l'L'l Sep 28 '14 at 07:52
  • I tried that and it didn't work, that is why I asked. That one still lets me type in numbers and accepts – Anthony Sep 28 '14 at 08:18

4 Answers4

9

Use /^[a-zA-Z]+$/ instead of /[a-zA-Z]/:

if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstname"]))
    $error = "<br />PLease enter a valid first name";

Explanation of the regexp:

  • ^ – To match start of the string.
  • [] – Matches the allowed characters.
  • + – To match one or more characters of the same type.
  • $ – To match end of string.
Nordehinu
  • 338
  • 1
  • 3
  • 11
nisargjhaveri
  • 1,469
  • 11
  • 21
1

In order to deal with unicode, you would use:

if (!preg_match("/^[- '\p{L}]+$/u", $_POST["firstname"]))
    $error = "<br />PLease enter a valid first name";

I've added the /u modifier for unicode and characters - ' for matching firstname like Jean-François

Toto
  • 89,455
  • 62
  • 89
  • 125
0

Anchor your match. See this code:

if ( !preg_match("/^[a-zA-Z]+$/", $_POST["firstname"]))
    $error = "<br />PLease enter a valid first name";
  • ^ and $ asserts thes tart and end of the match.

PS You may have misspelled "Please" in your code - "L" is in caps.

Nordehinu
  • 338
  • 1
  • 3
  • 11
-2

Well, I'm not a regex expert but you can just create a function that will check precisely what you need. It'd go somewhere along those lines (that function only checks for lower cases though):

$w = "hereisastr";
$i = 0;
while (isset($w[$i]))
{
  if ($w[$i] >= 'a' && $w[$i] <= 'z')
  {
    $i++;
  } else
  {
    return false;
    break;
  }
  return true;
}
bastienbot
  • 123
  • 1
  • 14