本节主要内容:
一个PHP自动生成关键字内链的类
代码:
<?php
/**
* php自动生成关键字的内链
* by www.jb200.com
*/
include_once(dirname(__file__)."/../db/DBViewSpot.php" );
class InnerLink{
private static $spotUrlMap;
/**
* Generate view spots keywords link
*
* @param string $description
* @param array $spotUrlMap
* @return string
*/
public static function genSpotLink($basePath, $description)
{
if(empty(InnerLink::$spotUrlMap)){
InnerLink::$spotUrlMap = DBViewSpot::getSpotPare();
}
// 排除不规则数据
if ( empty($description)) {
return $description;
}
foreach (InnerLink::$spotUrlMap AS $spotUrlPair){
$replace = "<a target='_blank' href='http://pzg412403.blog.163.com/blog/".$basePath."/".$spotUrlPair[1].".html'>".$spotUrlPair[0]."</a>";
// 描述里面只有文字,没有图片,所以只要注意 a 链接
$tmp1 = explode("<a",$description);
$is_replaced=false;
foreach ($tmp1 as $key=>$item){
$tmp2 = explode("</a>",$item);
if (sizeof($tmp2)>1) {
if (substr($tmp2[0],0,1)!="a" && substr($tmp2[0],0,1)!="A"){
if ($is_replaced===false) {
$tmp2[1] = InnerLink::str_replace_once($spotUrlPair[0],$replace,$tmp2[1],$is_replaced);
}
$tmp1[$key] = implode("</a>",$tmp2);
}
}else {
if (is_string($item) && $is_replaced===false) {
$tmp1[$key] = InnerLink::str_replace_once($spotUrlPair[0],$replace,$item,$is_replaced);
}
}
}
$description = implode("<a",$tmp1);
}
return $description;
}
/**
* replace key word for one time
*
* @param string $needle
* @param string $replace
* @param string $haystack
* @param bool $is_replaced
* @return string
*/
private static function str_replace_once($needle, $replace, $haystack,&$is_replaced) {
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
$is_replaced=true;
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
}