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

5
  • looks like this has been answered. stackoverflow.com/questions/6798745/… Commented Nov 20, 2019 at 22:58
  • @shobeurself not quite the same as it doesn't have the condition on sequences of ' and - Commented Nov 20, 2019 at 23:00
  • Does this answer your question? Regular expression for validating names and surnames? Commented Nov 20, 2019 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. Commented Nov 20, 2019 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. Commented Nov 21, 2019 at 11:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.