PHP正则表达式检查英文名称 [英] PHP regex to check a English name
问题描述
寻找一个正则表达式来检查一个有效的英文名称,即:
Looking for a regex to check a valid English name, i.e.:
- 仅 A-Z、a-z、
空格
- 名字,(可选)中间名,姓氏
一个可接受的例子:John von Neumann
谢谢!
编辑(添加检查代码):
EDIT (added checking code):
#!/usr/bin/php
<?php
function check_name($regex, $name)
{
$rc = 'Bad';
if (preg_match($regex, $name)) {
$rc = 'Good';
}
return '|' . $name . '| ' . $rc . "\n";
}
$regex = '/(?:[A-Za-z]+(?:\s+|$)){2,3}/';
echo check_name($regex, 'First');
echo check_name($regex, 'First Last');
echo check_name($regex, 'Two Spaces');
echo check_name($regex, 'First Middle Last');
echo check_name($regex, 'First Middle Last Fourth');
echo check_name($regex, 'First 123');
?>
推荐答案
如果您所陈述的规则确实是您想要的,那么以下方法可行:
If the rules you've stated are actually what you want, the following would work:
/^(?:[A-Za-z]+(?:\s+|$)){2,3}$/
但是,现实生活中有不少名字不符合这些规则,例如O'Malley"、Jo-Jo"等.
However, there are quite a few real-life names that don't fit in these rules, like "O'Malley", "Jo-Jo", etc.
你当然可以很容易地扩展这个正则表达式以允许其他字符 - 只需将它们添加到括号中即可.例如,要允许撇号和破折号,您可以使用 [A-Za-z'-]
(-
必须在末尾,否则将被解释作为一个范围).
You can of course extend this regex fairly easily to allow other characters - just add them into the brackets. For instance, to allow apostrophes and dashes, you could use [A-Za-z'-]
(the -
has to be at the end, or it will be interpreted as a range).
这篇关于PHP正则表达式检查英文名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!