正则表达式匹配从第一个大写到查询字符串的句子结尾


Regex to match from first uppercase to end of sentence of querystring

我需要找到一个或多个句子,是/是围绕一个字符串。这将是从第一个大写字母或换行到结束点或换行。

我得到的是这个,当然它根本不起作用:

$search_string='example';
$regex = ''[A-Z]{1}[a-z]*'s*'.$search_string.''s*[a-zA-Z]*'i';
preg_match_all($regex, $content, $matches);  

如果这个词在多个句子中重复,我将需要检索两个句子。我不确定我是否解释得很好;请评论,我会再解释一遍。


编辑

我有一个wordpress网站,里面有很多帖子和pdf,文档等。我使用一个名为swish-e的搜索引擎来索引所有结果并显示结果。当有人搜索任何字符串时,我想显示该字符串的摘要,而不是完整的post/或pdf。

因此,如果用户搜索"example"字符串,我需要显示所有句子或至少其中几个出现了单词example。这就是为什么我要求开头大写,结尾大写的原因。我知道这并不完美,但至少我需要涵盖一些场景(大写字母/换行等)

希望它更清楚,再次感谢

您的search_string应该使用preg_quote,或者用户可以使用特殊字符操作结果,如|

$search_string='example';
$regex = '/[A-Z][a-z ]*'b'.preg_quote($search_string,"/").''b.*?(?:[.!?]|$)/i';
preg_match_all($regex, $content, $matches);  

我假设这个句子可以用。还是?或!

你可能不想使用'字符作为你的模式分隔符——如果它能工作,它很可能会产生奇怪的行为。您还将i模式修饰符应用于您的模式,因此[a-z]也将匹配大写字母,而[a-z]将匹配小写字符。

编辑:

这个解决方案更灵活,尽管它不要求句子以大写字母开头。如果你想使用它,由你决定:

$search_string='example';
$regex = '/[^.!?'n]*'b'.preg_quote($search_string,"/").''b[^.!?'n]*/i';
preg_match_all($regex, $content, $matches);  

这个正则表达式可以满足你的要求:

$regex = '/[A-Z'n]{1}([a-z]*?'s*)+'.$search_string.'('s*?[a-zA-Z]*)+['.'n]/';

在这里你可以看到它是如何工作的:

http://ideone.com/aCJJZ

如何:

$search=preg_quote('example');
$regex = '/[A-Z][^'.]+'s+'.$search.''s[^'.]+/i';
preg_match_all($regex, $content, $matches);  
基本上

:

  • 大写字母
  • 一个或多个非.
  • 一个或多个空格
  • 你的模式
  • 一个或多个不是点的东西

应该匹配不包含结尾的.的句子


这是一个更完整的解决方案,(检查和工作)处理'转到下一行'的问题,以及被引号包围的单词:

$content = "Sentence one. This is an example sentence. Sentence two. Sentence with the word 'example' in it'nthat goes over multiple lines. this isn't starting with a capital letter, for example.";
$search=preg_quote('example');
$regex = '/[A-Z][^'.'n]+'W'.$search.''W[^'.'n]+/';
preg_match_all($regex, $content, $matches);  
print_r($matches);

打印:

Array
(
    [0] => Array
        (
            [0] => This is an example sentence
            [1] => Sentence with the word 'example' in it
        )
)