你想要的是一个正则表达式,特别是 preg_replace 或 peg_replace_callback (建议在你的情况下使用回调)
<?php
$searchString = "The car is driving in the carpark, he's not holding to the right lane.\n";
// define your word list
$toHighlight = array("car","lane");
因为您需要一个正则表达式来搜索您的单词,并且您可能希望或需要随时间变化或变化,所以将其硬编码到您的搜索词中是不好的做法。因此,最好使用 array_map 遍历数组并将搜索词转换为正确的正则表达式(这里只是用 / 括起来并添加“接受所有内容直到标点符号”表达式)
$searchFor = array_map('addRegEx',$toHighlight);
// add the regEx to each word, this way you can adapt it without having to correct it everywhere
function addRegEx($word){
return "/" . $word . '[^ ,\,,.,?,\.]*/';
}
接下来,您希望将找到的单词替换为突出显示的版本,这意味着您需要进行动态更改:使用 preg_replace_callback 而不是常规的 preg_replace ,以便它为找到的每个匹配项调用一个函数并使用它来生成正确的结果。在这里,我们将找到的单词包含在其 span 标签中
function highlight($word){
return "<span class='highlight'>$word[0]</span>";
}
$result = preg_replace_callback($searchFor,'highlight',$searchString);
print $result;
产量
The <span class='highlight'>car</span> is driving in the <span class='highlight'>carpark</span>, he's not holding to the right <span class='highlight'>lane</span>.
因此,显然只需将这些代码片段粘贴在另一个之后即可获得工作代码。;)
编辑:下面的完整代码稍作修改=放置在例程中,以便原始请求者使用。+ 不区分大小写
完整代码:
<?php
$searchString = "The car is driving in the carpark, he's not holding to the right lane.\n";
$toHighlight = array("car","lane");
$result = customHighlights($searchString,$toHighlight);
print $result;
// add the regEx to each word, this way you can adapt it without having to correct it everywhere
function addRegEx($word){
return "/" . $word . '[^ ,\,,.,?,\.]*/i';
}
function highlight($word){
return "<span class='highlight'>$word[0]</span>";
}
function customHighlights($searchString,$toHighlight){
// define your word list
$searchFor = array_map('addRegEx',$toHighlight);
$result = preg_replace_callback($searchFor,'highlight',$searchString);
return $result;
}