你想要的是(回拨你的情况将被推荐)正则表达式,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,以便它为每个找到的匹配调用一个函数,并使用它来生成正确的结果。在这里,我们在它的跨度标签
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;
}
Ty非常感兴趣...我有一个funtion.php文件。我会复制那里的功能,但不知道在哪里粘贴其他部分。 – webmasters
我在下面添加了一个完整的代码,供您复制/粘贴:) –
非常感谢,请允许我试试:)我是一名seo,web开发人员,有时候可以通过程序员帮助,真的,真的帮助:) – webmasters