如何在php中突出显示完整单词和部分单词?
下面是我的代码,我想突出显示一个完整单词和一个部分单词。下面的代码只突出显示完整单词,而不是部分单词 例如:如何在php中突出显示完整单词和部分单词?,php,regex,algorithm,Php,Regex,Algorithm,下面是我的代码,我想突出显示一个完整单词和一个部分单词。下面的代码只突出显示完整单词,而不是部分单词 例如: $text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance"; 及 我希望输出如下所示:- “这是李胡写的一首非常著名的诗,这篇文章想给重要的留下深刻印象” 我为其创建的函数:- function highlight($text, $wor
$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance";
及
我希望输出如下所示:-
“这是李胡写的一首非常著名的诗,这篇文章想给重要的留下深刻印象”
我为其创建的函数:-
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);
}
函数突出显示($text,$words){
preg_match_all(“~\w+~”,$words,$m);
如果(!$m)
返回$text;
$re='~\\b('.内爆('|',$m[0])。\\b~i';
返回preg_replace($re,$0',$text);
}
当您在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);
?>
如果不想匹配整个单词,请删除\b
。看看$words字符串是否同时包含部分和完整单词,然后我想突出显示部分和完整单词突出显示。那么,单词边界有什么好处呢?
<?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);
?>