php文章內容替換為內鏈,有助於SEO優化

小虎哥-技術部落格發表於2018-03-07

/**
 * 文章內容替換為內鏈
 * @param $content
 * @return mixed
 */
function get_glo_keywords($content)
{
    /* 這裡可以改為讀取資料表,然後快取起來 */
    $keywords_list = array(
        ['title'=>'小程式', 'url'=>'http://www.xin-shidai.com'],
        ['title'=>'導航網址', 'url'=>'http://www.xin-shidai.com'],
    );
    if($keywords_list){
        $readnum = 0;
        foreach ($keywords_list as $key => $val) {
            $title = $val['title'];
            $len = strlen($title);
            $str = '<a href="'.$val['url'].'" target="_blank">'.$title.'</a>';
            $str_index = mb_strpos($content, $title);
            $content = preg_replace('/(?!<[^>]*)'.$title.'(?![^<]*>)/', $str, $content, 1);
            if(is_numeric($str_index)){
                $readnum += 1;
                //$content = substr_replace($content,$str,$str_index,$len);
                //$content = $this->str_replace_limit($title,$str,$content,$this->limit);
            }
            if($readnum == 8) return $content; //匹配到8個關鍵詞就退出
        }
    }
    return $content;
}

相關文章