你想要的是(回撥你的情況將被推薦)正則表達式,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