PHP实现在文章中加内链的实例(只替换一次)

函数作用,只替换一个字符
$needkeywords --- 需要替换的字符串
$replacekeywords --- 替换成什么字符串
$content --- 需要操作的字符串
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);
       }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值