我怎么能用preg_match_all在大海捞针


How can I find a plural needle in haystack with preg_match_all?

下面是我出色的总结字符串函数:

function summarize($haystack, $needle, $wordLimit=1) {
    $preg_safe = str_replace(" ", "'s", preg_quote($needle));
    $pattern = "/('w*'S's+){0,$wordLimit}'S*'b($preg_safe)'b'S*('s'S+){0,$wordLimit}/ix";
    if (preg_match_all($pattern, $haystack, $matches)) {
        return $matches[0][0];
    }
    return false;
}

此函数在一个大字符串中查找指针,并将其与指针周围的n上下文单词一起返回。有点像谷歌搜索结果在标题下的结果上下文中显示搜索字符串。

以下是我的使用方法:

$haystack = 'Lorem ipsums dolor sit amet.'; // note the plural "ipsum"
echo summarize($haystack,'ipsums');

返回:Lorem ipsums dolor(默认为针周围的1个单词)

echo summarize($haystack,'ipsum'); // i.e. not exact word match of "ipsums"

返回:false

如何调整正则表达式以返回相同的结果-完全匹配的单词?

为了传递您的示例,您可以简单地在单词末尾允许一个可选的s。例如:

"/('w*'S's+){0,$wordLimit}'S*'b(${preg_safe}s?)'b'S*('s'S+){0,$wordLimit}/ix"

但这可能还不够。