获取正则表达式的上下文

时间:2017-05-21 09:12:34

标签: php regex

我想获得搜索字符串的上下文,我的第一种方法就是这个正则表达式:

!\.(.{20,})' . $string . '(.{20,})\.!

适用于<{p>中的The fox is jumping in the garden

  

是。这只鸟在风中飞舞。当他快乐的时候,狐狸正在花园里跳跃。但这不是全部。

但不适用于

  

这只鸟在风中飞舞。当他快乐的时候,狐狸正在花园里跳跃。但这不是全部。

因为缺少第一个点。所以我需要一些点或字符串的开头。

但是我仍然会遇到问题

  

当他快乐时,狐狸正在花园里跳跃。但这不是全部。

甚至

  

是。当他快乐的时候,狐狸正在花园里跳跃。但这不是全部。

我想拥有尽可能多的内容(说实话,60个字符会好于20个字符)。但是我也希望它在没有更多字符的情况下工作。我怎样才能做到这一点?

https://regex101.com/r/P3sFTw/1

编辑:对不起,我应该说,我总是希望将完整的句子作为上下文。所以说:左边和右边最少60个字符(如果存在),但不要剪切句子并将60个字符扩展到下一个点(或字符串的开头)。

3 个答案:

答案 0 :(得分:0)

$testArray = [
    'Yes. The bird is flying in the wind. The fox is jumping in the garden when he is happy. But that is not the whole story.' => '...The fox is jumping in the <strong>garden</strong> when he is happy. But that...',
    'The bird is flying in the wind. The fox is jumping in the garden when he is happy. But that is not the whole story.'      => '...The fox is jumping in the <strong>garden</strong> when he is happy. But that...',
    'The fox is jumping in the garden when he is happy. But that is not the whole story.'                                      => '...is jumping in the <strong>garden</strong> when he is happy...',
    'Yes. The fox is jumping in the garden when he is happy. But that is not the whole story.'                                 => '...fox is jumping in the <strong>garden</strong> when he is happy...',
    'Yes. The fox is jumping in the garden when he is happy. But that is not the whole story of the garden story.'             => '...The fox is jumping in the <strong>garden</strong> when he is happy. But...',
];

- &GT;这里有一些测试结果:) via ...“extractText()”

$searchString = 'garden';
foreach ($testArray as $testString => $testExpected) {
  $stringy = S::create($testString);
  $result = $stringy->extractText($searchString)
                    ->replace($searchString, '<strong>' . $searchString . '</strong>')
                    ->toString();
  self::assertSame($testExpected, $result, 'tested: ' . $testString);
}

- &GT; https://github.com/voku/Stringy/

答案 1 :(得分:0)

编辑:在澄清问题之后,希望您有以后的信息(我确定您可以将其改为使用变量):

[^.]*.{0,20}The fox is jumping in the garden.{0,20}.*?(?:\.|$)

链接示例:

https://regex101.com/r/P3sFTw/5

ORIGINAL:您可以使用以下Regex:

(.{0,20})The fox is jumping in the garden(.{0,20})

链接示例:

https://regex101.com/r/P3sFTw/3

答案 2 :(得分:0)

  

所以我需要一些点或字符串的开头。

这个完成工作:

wedding