【发布时间】:2020-07-09 22:15:20
【问题描述】:
所以我有以下功能:
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(),这使得搜索本身不区分大小写(就像我想要的那样),但问题是我无法弄清楚如何突出显示大写和小写版本如果我以这种方式编写函数,则单词的正确性。
如果您需要对此进行澄清,请告诉我,我不确定我是否解释得很好
【问题讨论】: