You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP正则表达式需求:捕获带指定关键词前缀的姓名首字母+姓氏

解决PHP正则捕获指定关键词前缀后的首字母+姓氏姓名问题

Got it, I know you were struggling with a regex that was incorrectly picking up names like "A. General" when you only wanted to capture those prefixed by specific keywords (from, with, of, and, as, observed). Let's break down the working solution you found, with clear explanations and examples:

最终可用正则表达式

这里是经过验证能精准匹配的正则,我修正了首字母后的点(原正则里的.是通配符,需要转义成\.才能匹配实际的点号):

$regex = "/\b(?:from|with|of|and|as|observed|,)\s+([A-Z]\.\ \w+)/";

正则表达式逐段解释

  • \b:单词边界,确保我们匹配的是完整的关键词(比如不会把"fromxyz"里的"from"当成有效前缀)
  • (?:from|with|of|and|as|observed|,):非捕获分组,列出所有触发姓名捕获的前缀(指定关键词或逗号),?:表示这个分组的内容不会被加入最终的匹配结果,只用来定位位置
  • \s+:匹配一个或多个空白字符,处理前缀和姓名之间的空格(兼容多个空格的情况)
  • ([A-Z]\.\ \w+):核心捕获分组,匹配首字母大写+点号+空格+姓氏的格式,这个分组的内容就是我们要提取的目标姓名

使用示例

示例文本

The report was compiled by J. Doe, from S. Smith, with A. Johnson, of B. Williams, and C. Brown, as D. Davis, observed E. Miller. Also note A. General is not relevant.

PHP代码实现

// 示例文本
$text = "The report was compiled by J. Doe, from S. Smith, with A. Johnson, of B. Williams, and C. Brown, as D. Davis, observed E. Miller. Also note A. General is not relevant.";

// 正则表达式
$regex = "/\b(?:from|with|of|and|as|observed|,)\s+([A-Z]\.\ \w+)/";

// 执行匹配
preg_match_all($regex, $text, $matches);

// 提取捕获的姓名数组
$names = $matches[1];

// 输出结果
print_r($names);

期望输出数组

Array
(
    [0] => S. Smith
    [1] => A. Johnson
    [2] => B. Williams
    [3] => C. Brown
    [4] => D. Davis
    [5] => E. Miller
)

这个正则会自动跳过没有指定前缀的"A. General",只保留我们需要的目标姓名,完美解决你之前的误匹配问题。

内容的提问来源于stack exchange,提问作者tlorens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:19:28