先定义一个实现的方法类
function highlighter_text($text, $words)
{
$split_words = explode( " " , $words );
foreach($split_words as $word)
{
$color = "#4285F4";
$text = preg_replace("|($word)|Ui" ,
"<span style=\"color:".$color.";\"><b>$1</b></span>" , $text );
}
return $text;
}
写一个调用的案例
<?php
$string = "I like chocolates and I like apples";
$words = "apple";
echo highlighter_text($string ,$words);
?>