1. 程式人生 > >php文章內容內鏈功能,相同關鍵字只內鏈一次

php文章內容內鏈功能,相同關鍵字只內鏈一次

/**

 * 文章詳情匹配一次關鍵字內鏈
 *
 * @param  $content string 文章內容
 * @param  $arr     array  關鍵字陣列
 * @param  $url     string 內鏈url
 * @param  $suffix  string url字尾
 */
function articleInner($content, $arr, $url, $suffix='.html'){
    $regular = '<a .*>.*<\/a>|<img .*>|<iframe .*>.*<\/iframe>';
    $chunkeds = preg_split("/($regular)/Ui", $content, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);    
    $tagArr = array();

    foreach ($chunkeds as $k => $val) {
        $bool = preg_match("/($regular)/Ui", $val);  
        if(!$bool){
            foreach ($arr as $key => $value) {
                if(($position = strpos($val,$value['name']))!==false && !in_array($value['name'], $tagArr)){
                    $leng     = strlen($value['name']);
                    $replIntro = "<a href='".$url.$value['id'].$suffix."' target='_blank'>".$value['name']."</a>";
                    $val       =  substr_replace($val,$replIntro,$position,$leng);
                    $tagArr[]  = $value['name']; //記錄已內鏈的關鍵字
                }
            }
            $chunkeds[$k] = $val;
         }
    }
    return implode('', $chunkeds);
}