PHP - 显示带有 5 个周围单词的搜索单词

0 php search text words text-files

我刚来这地方。我有一个关于一些 PHP 的问题。我目前正在做一个项目。现在有一个问题。

所以,首先:我的“愿望”是什么:有一个文本文件,它包含如下内容:

John Brown: Lives in New York, married, have 3 sons and love playing football
Run Code Online (Sandbox Code Playgroud)

现在我需要一个 PHP 代码,它读取和搜索文本文件,但只显示特殊的搜索词,搜索词周围有 5 个词,所以结果应该是这样的:我正在搜索儿子,结果应该是: John Brown: Have 3 sons and love playing编辑:忘了说,名字John Brown应该留在搜索结果中。

请帮我。抱歉我的英语不好,住在德国:)

这是我迄今为止尝试过的:

<?php
$search = 'sons';
$lines = file('file.txt'); 
// Store true when the text is found 
$found = false;
foreach($lines as $line) { 
  if(strpos($line, $search) !== false) { $found = true; echo $line; } 
} 
// If the text was not found, show a message 
if(!$found) { echo 'No match found'; }
?>
Run Code Online (Sandbox Code Playgroud)

Jef*_*Jef 5

在这里,只是为了咧嘴笑,是一个循环遍历字符串计数空间而不是爆炸和内爆的解决方案:

function context_find($haystack, $needle, $context) {
    $haystack=' '.$haystack.' ';
    if ($i=strpos($haystack, $needle)) {
        $start=$i;
        $end=$i;
        $spaces=0;

        while ($spaces < ((int) $context/2) && $start > 0) {
            $start--;
            if (substr($haystack, $start, 1) == ' ') {
                $spaces++;
            }
        }

        while ($spaces < ($context +1) && $end < strlen($haystack)) {
            $end++;
            if (substr($haystack,$end,1) == ' ') {
                $spaces++;
            }
        }

        while ($spaces < ($context +1) && $start > 0) {
            $start--;
            if (substr($haystack, $start, 1) == ' ') {
                $spaces++;
            }
        }

        return(trim(substr($haystack, $start, ($end - $start))));
    } else {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

例如:

$h="Twas brillig and the slithy toves did gyre and gimbel in the wabe";
$n="toves";
$c="5";

print context_find($h, $n, $c)."\n";
Run Code Online (Sandbox Code Playgroud)

返回:

the slithy toves did gyre
Run Code Online (Sandbox Code Playgroud)

此外,即使搜索词太接近开头或结尾,它也会尝试返回适量的上下文:

$h="Twas brillig and the slithy toves did gyre and gimbel in the wabe";
$n="brillig";
$c="5";

print context_find($h, $n, $c)."\n";
Run Code Online (Sandbox Code Playgroud)

返回:

Twas brillig and the slithy
Run Code Online (Sandbox Code Playgroud)

甚至:

$h="Twas brillig and the slithy toves did gyre and gimbel in the wabe";
$n="wabe";
$c="5";
Run Code Online (Sandbox Code Playgroud)

返回:

and gimbel in the wabe
Run Code Online (Sandbox Code Playgroud)

当然,这对循环输入文件等没有任何作用,其他示例就足够了。