PHP在文件中搜索关键字(不区分大小写)



所以我有以下函数:

function findMatches($pathToDirectory, $keyword){
$results = array();
$htmlString = "";
$fileList = glob($pathToDirectory);
natsort($fileList);
foreach ($fileList as $search) {
$contents = file_get_contents($search);
$episodeTitle = fgets(fopen($search, 'r'));
$episodeTitle = "<p class='episode_title'>$episodeTitle</p>";
$sentences = preg_split('/(?<=[.])s+(?=[a-z])/i', $contents);
foreach ($sentences as $sentence) {
if (strpos($sentence, $keyword)) {
if (!in_array($episodeTitle, $results)) {
array_push($results, $episodeTitle);
}
array_push($results, $sentence);
}
}
}
foreach ($results as $result){
$highlightedKeyword = '<span class="keyword_highlight">' . $keyword . '</span>';
$newResult = str_replace($keyword, $highlightedKeyword, $result);
$htmlString .= '<p class="search_result">' . $newResult . '</p>';
}
$totalResults = 'Total Results: <span class='number_result'>' . count($results) . '</span>';
return $htmlString = $totalResults . $htmlString;
}

它打开目录中的每个文本文件($filelist(,获取其内容,将其拆分为句子($sentences(,然后将包含用户定义关键字的句子保存到数组中($results(。然后,它通过$results迭代,将关键字包装在HTML中(这样单词就会在句子中突出显示给用户(,最后它将每个句子包装在HTML,并将它们发送给用户。

但是,目前该函数区分大小写。有什么好方法可以使其不区分大小写?我尝试在foreach ($sentences as $sentence)循环中使用stripos()而不是strpos(),这使得搜索本身不区分大小写(就像我想要的那样(,但问题是,如果我用这种方式编写函数,我不知道如何正确地突出显示单词的大小写版本。

此外,如果你需要澄清这些,请让我知道,我不确定我解释得太好了

高亮显示时需要使用stripos()str_ireplace()

最新更新