突出显示给定字符串中的多个关键字 [英] Highlight multiple keywords from a given string

查看:99
本文介绍了突出显示给定字符串中的多个关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使字符串只是一个单词,我也需要从字符串中突出显示每个单词.

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';

$string = 'This shouldbebolded';

预期结果:

应被固定". 这是类似Google的亮点.

"This shouldbebolded." This is the Google like highlight.

推荐答案

您可以使用 explode foreach str_replace :

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;

?>

结果将是:

我的电视

这篇关于突出显示给定字符串中的多个关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆