PHP正则表达式围绕搜索短语的单词集合

时间:2011-10-12 16:19:01

标签: php regex

您好我正在尝试创建一个将执行以下操作的正则表达式

在搜索短语之前抓取5个单词(如果那里只有x个单词则为x),在搜索短语之后抓取5个单词(或者如果只有x个单词则为x)从一个文本块中抓取(当我说出单词I时意思是文字块中的单词或数字。

例如

欢迎使用Stack Overflow!访问您的用户页面以设置您的姓名和电子邮件。

如果您要搜索“访问”,它将返回: 欢迎来到Stack Overflow!访问您的用户页面以设置

这个想法是在php中使用preg_match_all给我一堆搜索结果,显示搜索短语每次出现时在文本中出现的位置。

提前致谢:D

在子笔记上可能有一个更好的方法来获得我的结果,如果你觉得有请随意把它扔进游泳池,因为我不确定这是我认为的第一种方式是最好的,做我需要的:D

2 个答案:

答案 0 :(得分:8)

这个怎么样:

(\S+\s+){0,5}\S*\bvisit\b\S*(\s+\S+){0,5}

将匹配搜索词之前和之后的五个“单词”(但文字较短时接受较少)(在本例中为visit)。

preg_match_all(
    '/(\S+\s+){0,5} # Match five (or less) "words"
    \S*             # Match (if present) punctuation before the search term
    \b              # Assert position at the start of a word
    visit           # Match the search term
    \b              # Assert position at the end of a word
    \S*             # Match (if present) punctuation after the search term
    (\s+\S+){0,5}   # Match five (or less) "words"
    /ix', 
    $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

我将“单词”定义为非空格字符序列,由至少一个空格分隔。

搜索词应该是实际的词(以字母数字字符开头和结尾)。

答案 1 :(得分:1)

您可以执行以下操作(它的计算量很大,因此对于很长的字符串来说效率不高):

<?php
$phrase = "Welcome to Stack Overflow! Visit your user page to set your name and email.";
$keyword = "Visit";
$lcWords = preg_split("/\s/", strtolower($phrase));
$words = preg_split("/\s/", $phrase);
$wordCount = 5;

$position = array_search(strtolower($keyword), $lcWords);
$indexBegin =  max(array($position - $wordCount, 0));
$len = min(array(count($words), $position - $indexBegin + $wordCount + 1));
echo join(" ", array_slice($words, $indexBegin, $len));
//prints: Welcome to Stack Overflow! Visit your user page to set

Codepad example here

相关问题