从包含特定短语的文本中提取句子

时间:2014-06-30 01:06:19

标签: php regex

我有一个包含2个句子的文本文件:

stack overflow is the best. hello stack.

(末尾的点表示句子的结尾。)

如果句子包含the best

,如何从文本中提取整个句子

并输出包含the best的整个句子:

输出:stack overflow is the best.

没有尝试过。我应该使用什么样的正则表达式?

2 个答案:

答案 0 :(得分:3)

使用正则表达式打印包含the best的所有句子

$contents = file_get_contents("file.txt");
$sentences = explode('.',$contents);

foreach($sentences as $sentence) {
    if(false !== strpos($sentence,'the best'))
        print trim($sentence) . "\n";
}

Demo

答案 1 :(得分:1)

以下正则表达式将匹配包含best的文本到下一个文字点。

(?:^|\.)\K.*?(?=best)[^\.]*\.

DEMO

相关问题