教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP文章内链实例代码 php关键词替换且只替换一次

PHP文章内链实例代码 php关键词替换且只替换一次

发布时间:2017-02-23   编辑:jiaochengji.com
本文分享一例php代码,实现文章内容中关键词的替换,即实现文件内链的功能,本代码的亮点是:可以只替换一次。有需要的朋友参考下吧。

本节主要内容:
一个php实现的文章内链代码。

说明:本函数可以只替换一个字符。
函数参数:
 

$needkeywords --- 需要替换的字符串
$replacekeywords --- 替换成什么字符串
$content --- 需要操作的字符串

代码:
 

复制代码 代码示例:

<?php
/**
* 文章内链、关键词替换
* by www.jbxue.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);
    }
}

您可能感兴趣的文章:
php替换html内容的小函数
PHP文章内链实例代码 php关键词替换且只替换一次
PHP实现文章内容添加内链关键词替换的代码
php自动给文章加关键词链接的实现代码
php实现文章中关键词加链接的方法
PHP字符串替换函数 可同时替换多个关键词
php添加关联链接的代码
php自动给文章加关键词链接的代码
php实现特殊字符的替换操作
php关键词替换的类(避免重复替换,保留与还原原始链接)

[关闭]
~ ~