我们怎样才能在php中突出显示完整的单词和部分单词?

时间:2017-01-02 09:40:36

标签: php regex algorithm

下面是我的代码,我想要突出显示一个完整的单词和一个部分单词。下面的代码只是突出显示完整字,而不是部分字。

例如:

$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance";

$words ="very written hu want impor";

我想要如下输出: -

“这是非常着名诗歌 by liegh hu 想要给帖子留下深刻印象的祁门功夫孟清湘“;

我为它创建的功能: -

function highlight($text, $words) {
    preg_match_all('~\w+~', $words, $m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
    return preg_replace($re, '<b style="color:white;background-color:red;border-radius:2px;">$0</b>', $text);
}

1 个答案:

答案 0 :(得分:1)

当你在php中使用内置函数时,不要再使用正则表达式了。

与纯PHP相同的功能。不使用正则表达式,忽略区分大小写。

<?php

 $words = "very written hu want impor";
 $words = explode(' ', $words);

function hilight($text, $words){
   foreach ($words as $value) {
    $text = str_ireplace($value,'<b style="color:white;background-color:red;border-radius:2px;">'.$value.'</b>',$text);
   }
  return $text;
}

$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance";
echo hilight($text, $words);

?>

enter image description here