PHP preg_match (_all) 文本范围

PHP preg_match (_all) for text range

尝试获取 Textrange(前后 n 个词)搜索字符串(我自己)

$text = 'Me, my dog and “myself“ are going on a vacation. Irene and myself are broke. Myself is here :P John and myself!';

 preg_match_all("/(?:[^ ]+ ){0,2}(?:[“'"(‘. ])myself(?:[“'")‘. ])(?: [^ ]+){0,2}/", $text, $matches);   

这给了我火柴:

• 狗和“我自己”要去

• 我自己

但应该是:

• 狗和“我自己”要去

• 艾琳和我都破产了

• 约翰和我!

请帮我找到所有匹配的文本范围,前 2 个词和后 2 个词。 无论搜索字符串 (myself) 或 'myself' 或“myself”前后是否有特殊字符或空格 ...

thanks.Sepp

问题的出现是因为 [“'"(‘. ][“'")‘. ] 都是强制性的,并且需要在 myself 前后各有一个字符。那么,(?:[^ ]+ ){0,2}(?: [^ ]+){0,2}所要求的myself前后一定还要有一个space。

您可以使用

'/(?:\S+\s+){0,2}(?:[“'"(‘.])?myself(?:[“'")‘.]?)(?:\s+\S+){0,2}/u'

或者允许 myself 周围的任何标点符号 \p{P}:

'/(?:\S+\s+){0,2}\p{P}?myself\p{P}?(?:\s+\S+){0,2}/u'

regex demo

请注意,(?:[“'"(‘.])?(?:[“'")‘.]?)(或 \p{P}?)都是可选的,它们后面的 ? 量词使正则表达式引擎仅匹配 1 次或 0 次出现这些图案。所以,无论是否存在,匹配都会发生。

PHP demo:

$text = 'Me, my dog and “myself“ are going on a vacation. Irene and myself are broke. Myself is here :P John and myself!';
if (preg_match_all('/(?:\S+\s+){0,2}\p{P}?myself\p{P}?(?:\s+\S+){0,2}/u', $text, $result)) {
    print_r($result[0]);
}

输出:

Array
(
    [0] => dog and “myself“ are going
    [1] => Irene and myself are broke.
    [2] => John and myself!
)