dqpwdai095465 2017-08-22 09:26 采纳率: 100%
浏览 71
已采纳

preg_match匹配组的名字/姓氏

I'm using this PHP regexp to check true/false whether a field contains a name, consisting of at least a first/last name, and then optional other middle names or initials.

$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];

Seems to work fine in terms of hits/misses, i.e. true/false whether it matches or not.

But then I'm trying to use the same thing to extract the first and last names using groups, which I'm struggling to get right..

Get lots of results like:

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

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

  "matches": [
    "Jonathan M Notty",
    "n",
    " M",
    "M",
    "Notty"
  ]

..but what I really want is for one of the 'matches' to always contain just the first name, and one to contain always just the last name.

Any pointers as to what's wrong?

  • 写回答

3条回答 默认 最新

  • duanchun1881 2017-08-22 09:59
    关注

    Whenever you define a capturing group in a regular expression, the part of string it matches is added as a separate item in the resulting array. There are two strategies to get rid of them:

    • Optimize the pattern and get rid of the redundant groups (e.g. groups around single atoms - (a)+ => a+)
    • Turn capturing groups into non-capturing ((\s+\w+)+ => (?:\s+\w+)+)

    Also, in your case, you may enhance the patter if you replace the letter matching part with the \p{L} Unicode property class that matches any letters.

    Use

    /[\p{L}'-]{2,}(?:\s[\p{L}'-]+)?\s[\p{L}'-]{2,}/u
    

    See the regex demo

    Here, only one grouping is left, (?:...), and it is optional, the ? after it makes it match 1 or 0 times.

    Details

    • [\p{L}'-]{2,} - 2 or more letters, ' or -
    • (?:\s[\p{L}'-]+)? - 1 or 0 occurrences of a whitespace and then 1 or more letters, ' or -
    • \s - a whitespace
    • [\p{L}'-]{2,} - 2 or more letters, ' or -
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?