当前位置 : 主页 > 网络编程 > PHP >

PHP搜索和高亮字符串中的关键字

来源:互联网 收集:自由互联 发布时间:2021-06-30
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 $te
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);
?>
网友评论