本节主要内容:
一个php实现的文章内链代码。
说明:本函数可以只替换一个字符。
函数参数:
 
代码:
 
<?php
/**
* 文章内链、关键词替换
* by www.jb200.com
*/
function str_replace_once($needkeywords, $replacekeywords,$content ) {
   $pos = strpos($content, $needkeywords);
   if ($pos === false) {
      return $content ;
   }
   return substr_replace($content, $replacekeywords, $pos, strlen($needkeywords));
}
//$_GET['data']:把要替换的关键词ID用","号隔开放在data中
//$_GET['ClassID']:要传入的分类ID,判断要替换的文章的关键词内链
//keywords_set:为要导入的关键词表
if(isset($_GET['data'])){
    $keyrowds=explode(",",$_GET['data']);   
    foreach($keyrowds as $val){
//根据ID查询关键词表
        $sqlkey="select *from keywords_set where ID=".$val;
        $resultkey=@mysql_query($sqlkey);
        $rowskey=mysql_fetch_assoc($resultkey);
//取出关键词及其相关链接路径装入$contents中
        $contents[]=array(
        'Name'=>$rowskey['Name'],
        'LinkUrl'=>$rowskey['LinkUrl']
        );
    }
//article:文章表,通过$_GET['ClassID']提取所有要替换的文章
    $Sql="select* from article where classID='".$_GET['ClassID']."'";
    $Result=@mysql_query($Sql);
    while($rows=mysql_fetch_assoc($Result))
    {
        $contentkey=$rows['content'];//文章内容字段
        foreach($contents as $value){
//更新关键词库
        $sqlupdate="update keywords_set set PostAddtime='".date("Y-m-d",time())."' where Name='".$value['Name']."'";
        $resultupdate=@mysql_query($sqlupdate);//执行更新sql语句
        //组合成内链
            $contentkeys="".$value['Name'].""; 
//判断如果为导入内链则替换,否则去掉替换         
            if($_GET['flg']=="insert"){
                $contentkey=str_replace_once($value['Name'],$contentkeys,$contentkey);
            }
            if($_GET['flg']=="out"){
            $contentkey=str_replace($contentkeys,$value['Name'],$contentkey);
            }
        }
        //更新文章内链
        $sqlupdate="update article set content='".$contentkey."' where articleID=".$rows['articleID'];
        $resultupdate=@mysql_query($sqlupdate);
    }
}