突出显示提取的描述中提取的关键字

时间:2013-12-27 19:31:29

标签: php

好的,假设我们想获得网站的标题,关键字和描述,那么我将使用以下功能

<?PHP

function getInfo($URL)
{
    $getInfo= get_meta_tags($URL);
    return $getInfo;
}

$URL = "http://www.my_site.com"; // URL

// Applying the function
$_getInfo = getInfo($URL);

// Print the results.

echo $_getInfo ["keywords"]."<br>"; // gives keywords
echo $_getInfo ["description"]."<br>"; // gives description

?>

然而,一切都很好,但假设结果如下

关键字

php,profitable,share

描述

Advanced profitable and featured script to share

在此示例中,我们在说明profitableshare

中找到了一些关键字

问题是如何突出仅在描述中找到的关键字!!

我将添加以下css

<style>
.highlight{background: #CEDAEB;}
.highlight_important{background: #F8DCB8;}
</style>

并将添加此功能以在两种不同颜色之间进行更改,就像在css代码

中一样
<?PHP
    function hightlight($str, $keywords = '')
    {
        $keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
        $style = 'highlight';
        $style_i = 'highlight_important';
        $var = '';
        foreach (explode(' ', $keywords) as $keyword) {
            $replacement = "<span class='".$style."'>".$keyword."</span>";
            $var .= $replacement." ";
            $str = str_ireplace($keyword, $replacement, $str);
        }
        $str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
        return $str;
    }
?>

现在同时应用(不工作)

$string = hightlight($_getInfo["description"], $_getInfo ["keywords"]);
echo $string;

为什么不工作导致它将$_getInfo ["keywords"]定义为一个单词php,profitable,share 在那种形状的描述中确实没有找到。

所以如何应用使用explodeforeach(我猜)所以输出如下:

enter image description here

我想知道如果我看起来不是很好的方式,还有另一种方法可以做到这一点。 〜谢谢

1 个答案:

答案 0 :(得分:1)

由于您的关键字采用列表格式,因此您需要:

foreach(explode(',', $keywords) as $keyword)