Hoe to write a regex that validates middle initial in PHP. Because some people have more than one middle initial the regex should allow between one and and thee middle initials.
The regex should allow one letter with or wothout a period, two or three letters each followed by a period, or two or three letters each followed by a period and a single space.
Here is the list of allowed stings where ‘A’ means any letter of upper or lower case, including unicode letters in foreign alphabets:
'A', 'A.', 'A.A.', 'A. A.', 'A.A.A.', 'A. A. A.'
Here is a regex that I wrote as a starting point to validate exactly one midlle initial in English alpabet followed by an optional period.
$pattern = "/^([a-zA-Z]{1}[.]{0,1})?$/";
preg_match_all($pattern, $input_string, $match) > 0;
2
Answers
I guess much of this will depend on what you define as a valid name. EG?
The results will be:
Ok, so we will have 2 kinds of matches across the entire string.
A. A. A.
pattern where every character is followed by a.
.A A A
pattern where every character is followed by spaces and not period characters.As far as regex is concerned, it will be as below,
p{L}.s*
to matchA. A. A.
pattern. Thep{L}
is used to match a single Unicode codepoint.p{L}s*
to matchA A A
pattern.Overall, the regex will be
/^((p{L}.s*)+|(p{L}s*)+)$/iu
. The|
is used to indicate an alternative match. So, it could be either the first capturing group or the 2nd one. Theu
flag used to treat subject strings and patterns as UTF-8. (see more info
)Snippet:
Live Demo