Highlight multiple keywords from a given string

混江龙づ霸主 提交于 2019-12-13 22:07:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!