Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php preg_匹配名/姓匹配组_Php_Regex_Pattern Matching_Names - Fatal编程技术网

Php preg_匹配名/姓匹配组

Php preg_匹配名/姓匹配组,php,regex,pattern-matching,names,Php,Regex,Pattern Matching,Names,我使用这个PHP正则表达式来检查一个字段是否包含一个名称(至少包含一个名/姓),然后是可选的其他中间名或首字母缩写 $success = preg_match("/([\x{00c0}-\x{01ff}a-zA-Z'-]){2,}(\s([\x{00c0}-\x{01ff}a-zA-Z'-]{1,})*)?\s([\x{00c0}-\x{01ff}a-zA-Z'-]{2,})/ui",$user['name'],$matches); $output[($success ? 'hits' : '

我使用这个PHP正则表达式来检查一个字段是否包含一个名称(至少包含一个名/姓),然后是可选的其他中间名或首字母缩写

$success = preg_match("/([\x{00c0}-\x{01ff}a-zA-Z'-]){2,}(\s([\x{00c0}-\x{01ff}a-zA-Z'-]{1,})*)?\s([\x{00c0}-\x{01ff}a-zA-Z'-]{2,})/ui",$user['name'],$matches);

$output[($success ? 'hits' : 'misses')][] = ['id' => $user['id'],'email' => $user['email'],'name' => $user['name'],'matches' => $matches];
就命中/未命中而言,似乎工作正常,即无论匹配与否,都是真/假

但是我试图用同样的方法,通过分组来提取名字和姓氏,我正在努力做到这一点

获得许多结果,如:

  "name": "Jonny Nott",
  "matches": [
    "Jonny Nott",
    "y",
    "",
    "",
    "Nott"
  ]

  "name": "Name Here",
  "matches": [
    "Name Here",
    "e",
    "",
    "",
    "Here"
  ]

  "matches": [
    "Jonathan M Notty",
    "n",
    " M",
    "M",
    "Notty"
  ]
…但我真正想要的是其中一个“匹配项”始终只包含名字,另一个始终只包含姓氏

有什么问题吗?

试试:

(?P<firstName>[\x{00c0}-\x{01ff}a-zA-Z'-]{2,})(\s([\x{00c0}-\x{01ff}a-zA-Z'-]{1,})*)?\s(?P<lastName>[\x{00c0}-\x{01ff}a-zA-Z'-]{2,})
(?P[\x{00c0}-\x{01ff}a-zA-Z'-]{2,})(\s([\x{00c0}-\x{01ff}a-zA-Z'-]{1,})*)?\s(?P[\x{00c0}-\x{01ff}a-zA-Z'-]{2,})

你犯的主要错误是重复第一组{2,}-不是第一个范围

使用非捕获组
(?:…)
,只要你必须使用括号,但你不想匹配该部分(例如空格和中间名的一部分),并且在捕获组中包含一个量词,而不仅仅是要匹配的字符(例如,对于名字
{2,}
应在捕获组中)

无论何时在正则表达式中定义,它匹配的字符串部分将作为单独的项添加到结果数组中。有两种策略可以消除它们:

  • 优化模式并去除冗余组(例如单个原子周围的组-
    (a)+
    =>
    a++
  • 将捕获组转换为(
    (\s+\w+)+
    =>
    (?:\s+\w+)+
此外,在您的情况下,如果您将字母匹配部分替换为与任何字母匹配的
\p{L}
Unicode属性类,则可以增强模式

使用

在这里,只剩下一个分组,
(?:…)
,它是可选的,
在使其匹配1或0次之后

详细信息

  • [\p{L}'-]{2,}
    -2个或多个字母,
    '
    -
  • (?:\s[\p{L}-]+)
    -1次或0次出现空白,然后出现1个或多个字母,
    '
    -
  • \s
    -空白
  • [\p{L}'-]{2,}
    -2个或多个字母,
    '
    -
([\x{00c0}-\x{01ff}a-zA-Z'-]{2,})(?:\s(?:[\x{00c0}-\x{01ff}a-zA-Z'-]{1,})*)?\s([\x{00c0}-\x{01ff}a-zA-Z'-]{2,})
/[\p{L}'-]{2,}(?:\s[\p{L}'-]+)?\s[\p{L}'-]{2,}/u