Ben
Ben

Reputation: 33

Using a Regular Expression in PHP to validate a name

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

Upvotes: 2

Views: 539

Answers (1)

Nick
Nick

Reputation: 147166

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

Upvotes: 3

Related Questions