Reputation: 121
Below is my code, I want to highlight a full word and a partial word. The code below just highlights the full word but not the partial word.
For example :
$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance";
AND
$words ="very written hu want impor";
I want output like below :-
"this is a very famouse poem written by liegh hunt the post want to impress upon the importance";
Function that i have created for it:-
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);
}
Upvotes: 2
Views: 394
Reputation: 5912
Stop struggling with regular expressions when you have inbuilt functions in php.
Same functionality with pure php. without using regular expression, by ignoring case sensitive.
<?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);
?>
Upvotes: 1