PHP批量過濾MYSQL數(shù)據(jù)庫內站外鏈接和圖片
標簽:
發(fā)布日期:2014-05-04 22:54:00
1580
因發(fā)現(xiàn)站內很多引用站外文章的鏈接失效,產(chǎn)生大量的死鏈接,對于搜索引擎來說是極不友好的,很不利于網(wǎng)站優(yōu)化,所以站內添加了站外鏈接過濾功能,對于新加的文章,在添加入庫時就自動增加rel="nofollow"標簽,見文章《增加對站點內容外部鏈接的過濾》。因考慮如果是在前臺調用數(shù)據(jù)時過濾的話,對網(wǎng)頁打開速度,服務器能耗都增加許多,所以就采用的是入庫時添加。
那么,原來已有的數(shù)據(jù)怎么辦?現(xiàn)在需要對原來的數(shù)據(jù)也進行此操作,如果是在后臺一條條編輯來實現(xiàn),即使只需要點一下,工程量也是很大的,那么就需要一個批處理操作。
寫一個批處理程序即可,經(jīng)調試,測試,以下的程序可很好的替換原來數(shù)據(jù)庫里面的外部鏈接和外部圖片
如,站點是http://www.bbcq1.cn
一篇文章里有一個鏈接是 http://www.53sj.net/article-6-1.html
一個圖片是 http://www.53sj.net/data/attachment/block/d3/d34780d1fca3d6b7960a7eb7a2c4c0d3.jpg
經(jīng)過批處理操作后
其代碼變成 <a href="http://www.53sj.net/article-6-1.html" rel="external nofollow"
<img src="http://www.53sj.net/data/attachment/block/d3/d34780d1fca3d6b7960a7eb7a2c4c0d3.jpg" rel="external nofollow"
批量過濾MYSQL數(shù)據(jù)庫內站外鏈接和圖片程序代碼
global $config,$db;
$sql = "SELECT `id`,`content` FROM `{$db->prefix}article`";
$a_list = $db->query($sql);
$domain = $config['url'];
$domain = substr($domain,0,strlen($domain)-1); //修正當前域名網(wǎng)址
foreach($a_list as $a){
$content = content_nofollow($a['content'],$domain);
update_a($a['id'],addslashes($content));
}
exit;
function update_a($id,$content){
global $config,$db;
$sql = "update `{$db->prefix}article` SET `content`='{$content}' where `id`={$id}";
if($db->execute($sql)){echo $id.'更新成功!<br />';}
}
//外部鏈接增加nofllow $content 內容 $domain 當前網(wǎng)站域名
function content_nofollow($content,$domain){
preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,$domain)===false ) $content=str_replace('href="'.$val.'"', 'href="'.$val.'" rel="external nofollow" ',$content);
}
}
preg_match_all('/src="http:(.*?)"/',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,$domain)===false ) $content=str_replace('src="http:'.$val.'"', 'src="http:'.$val.'" rel="external nofollow" ',$content);
}
}
return $content;
}