问题
I need to highlight each word separately from a string, even if the string is only one word.
$keyword = 'should be bolded';
$string = 'This shouldbebolded';
Expected result:
"This shouldbebolded." This is the Google like highlight.
回答1:
You can do this using explode, foreach and str_replace:
<?php
# Keywords
$keywords_str = 'tv nice';
# String
$string = 'My tv is nice';
# Operation result(to not modify $string)
$result = $string;
# Split $keywords by spaces into array of single keywords
$keywords = explode(' ', $keywords_str);
# Loop keywords array
foreach($keywords as $keyword)
{
# Replace every keyword occurence to make it bold
$result = str_replace($keyword, "<b>$keyword</b>", $result);
}
echo $result;
?>
And the result would be:
My tv is nice
回答2:
A simple function will suffice your requirement. You can break your words into an array to search for all of them separately.
Simply use explode()
function to break your words into array and pass it to the function below.
function highlightWords($string, $words)
{
foreach ( $words as $word )
{
$string = str_ireplace($word, '<span class="highlight">'.$word.'</span>', $string);
}
return $string;
}
来源:https://stackoverflow.com/questions/9343064/highlight-multiple-keywords-from-a-given-string