2

Here i want to validate a name where:

A name only consist of these characters [a-zA-Z-'\s] however a sequence of two or more of the hyphens or apostrophe can not exist also a name should start with a letter.

I tried

$name = preg_match("/^[a-zA-Z][a-zA-Z'\s-]{1,20}$/", $name);

however it allows double hyphens and apostrophes. If you can help thank you

Ben
  • 45
  • 6
  • looks like this has been answered. https://stackoverflow.com/questions/6798745/regex-expression-for-name-validation – shobeurself Nov 20 '19 at 22:58
  • @shobeurself not quite the same as it doesn't have the condition on sequences of `'` and `-` – Nick Nov 20 '19 at 23:00
  • Does this answer your question? [Regular expression for validating names and surnames?](https://stackoverflow.com/questions/888838/regular-expression-for-validating-names-and-surnames) – AMC Nov 20 '19 at 23:00
  • @AlexanderCécile doesn't sound like OP is validation people's names. For one - the 20 character limit does not fit with those. It seems like it's usernames or displaynames for the system. So, the dupe doesn't seem to match. – VLAZ Nov 20 '19 at 23:03
  • Another idea to require a word character left to any `-` or single quote. This pattern won't allow a hyphen surrounded by space: [`/^(?:[a-z]|\b[\'-]|\h){1,20}$/i`](https://regex101.com/r/19GL0l/2/). – bobble bubble Nov 21 '19 at 11:21

1 Answers1

3

You can invalidate names containing a sequence of two or more of the characters hyphen and apostrophe by using a negative lookahead:

(?!.*['-]{2})

For example

$names = array('Mike Cannon-Brookes', "Bill O'Hara-Jones", "Jane O'-Reilly", "Mary Smythe-'Fawkes");
foreach ($names as $name) {
    $name_valid = preg_match("/^(?!.*['-]{2})[a-zA-Z][a-zA-Z'\s-]{1,20}$/", $name);
    echo "$name is " . (($name_valid) ? "valid" : "not valid") . "\n";
}

Output:

Mike Cannon-Brookes is valid
Bill O'Hara-Jones is valid
Jane O'-Reilly is not valid
Mary Smythe-'Fawkes is not valid

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95