-1

Suppose I have a form and in the form, there is an input field for the users to put their full names. I want only characters (A-Za-z) and spaces to be submitted by the users.

<form action='page2.php'>
    <input type='text' name='fullname'>
    <input type='submit' name='submit' value='Submit'>
</form>

I know, it can be done by html. But I want to check in page2 if user has typed anything without (A-Za-z) and spaces. How this check can be performed with php?

John Wink
  • 95
  • 1
  • 2
  • 11
  • Regex, or perhaps [ctype_alpha](http://php.net/manual/en/function.ctype-alpha.php)? – Jonnix Mar 28 '17 at 07:54
  • Possible duplicate of [Allow only \[a-z\]\[A-Z\]\[0-9\] in string using PHP](http://stackoverflow.com/questions/2896450/allow-only-a-za-z0-9-in-string-using-php) – Michael Krikorev Mar 28 '17 at 07:57
  • you can use `str_pos()` – 131 Mar 28 '17 at 07:57
  • `Basil d'Olivera` is a full name with blocked characters; as is `Tim Berners-Lee`, or names like `José` or `Étienne` or `François` [Falsehoods programmers believe about names](http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) – Mark Baker Mar 28 '17 at 08:17
  • The area where the website is available, people have names only with A-Za-z – John Wink Aug 09 '20 at 04:30

3 Answers3

1

Try this

if (!preg_match("/^[a-zA-Z]$/", $user)) {
    /// not match
}
paranoid
  • 6,799
  • 19
  • 49
  • 86
0

Regex is big for this kind of tasks. You can use this :

if (ctype_alpha(str_replace(' ', '', $name)) === false)  {
  $errors[] = 'Name must contain letters and spaces only';
}
FarZzTM
  • 105
  • 1
  • 2
  • 7
0

if you want to use regex then below is the code to check alphabet only

preg_match('/^[a-zA-Z]+$/', $string);
Sudhakar
  • 324
  • 3
  • 9