PHP多次在文本中找到关键字-在字符之前/之后显示

时间:2018-07-07 18:55:11

标签: php search substr strpos

我正在搜索文本字符串中的关键字。例如:假设我想找到单词“快乐”,并在书中显示多少次。然后,我想在该单词前后显示100个字符,并对找到的每个单词“ Happy”执行此操作。

我能够一次找到执行此操作的代码,但是如何对所有出现的关键字(在这种情况下为“ Happy”一词)执行此操作?

这是工作代码,它发现一次出现并在字符前后显示字符。

$text= $Content;
$find = 'Happy';
$result = strpos($text, $find);
echo substr($text,($result-100>0)?($result-100):0,100)." ".$find." "
.substr($text,$result+strlen($find),100); 

如何循环执行并查找所有出现的关键字?

3 个答案:

答案 0 :(得分:1)

根据this

这可以帮助您找到第二个

letter_counts = get_letter_counts(s) #returns something like [1, 1, 2] when given wall, since there is one w, one a, two ls
n_anagrams = factorial(len(s))

#account for overcounts
for letter_count in letter_counts:
    n_anagrams /= factorial(letter_count)

return n_anagrams

第三个参数是您搜索单词的偏移量。因此默认值为0。 factorial会将候选单词长度加到最后出现的位置,该位置是get_letter_counts的起点。

然后像递归或其他方式进行操作

答案 1 :(得分:1)

以下内容不区分大小写,并且还可以用于带重音符号的字符:

$out = [];
$find = 'Happy';
$charsBA = 100; // number of characters before / after
$offset = 0;
while(false !== ($pos = mb_stripos($text, $find, $offset, 'utf-8'))){
    $out[] = mb_substr($text, max(0, $pos-$charsBA), $charsBA*2+mb_strlen($find, 'utf-8'), 'utf-8');
    $offset = ++$pos;
}
print_r($out); // display found occurences

答案 2 :(得分:1)

也许这就是您需要的?

$key="sed";
$string = "/([\s\S]{0,100})$key([\s\S]{0,100})/i";
$matches=null;
$paragraph = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?";

if (preg_match_all($string, $paragraph, $matches)) {
  echo count($matches[0]) . " matches found";
}else {
  echo "match NOT found";
}


var_dump($matches[0]);