|
復制代碼 代碼如下:
/**
* 格式化內(nèi)容
* @param string $content 內(nèi)容最好統(tǒng)一用utf-8編碼
* @return string
* !本函數(shù)需要開啟tidy擴展
*/
function removeFormat($content) {
$replaces = array (
"/<font.*?>/i" => '',
"/<//font>/i" => '',
"/<strong>/i" => '',
"/<//strong>/i" => '',
"/<span.*?>/i" => '',
"/<//span>/i" => '',
"/<div.*?>/i" => "<p>",
"/<//div>/i" => "</p>",
"/<!--<.*?>*-->/i"=>'',
/* "/<table.*?>/i" => '',//遇到有表格的內(nèi)容就不要啟用
"/<//table>/i" => '',
"/<tbody.*?>/i" => '',
"/<//tbody>/i" => '',
"/<tr.*?>/i" => '<p>',
"/<//tr>/i" => '</p>',
"/<td.*?>/i" => '', */
"/style=.+?['|/"]/i" => '',
"/class=.+?['|/"]/i" => '',
"/id=.+?['|/"]/i"=>'',
"/lang=.+?['|/"]/i"=>'',
//"/width=.+?['|/"]/i"=>'',//不好控制注釋掉
//"/height=.+?['|/"]/i"=>'',
"/border=.+?['|/"]/i"=>'',
"/face=.+?['|/"]/i"=>'',
"/<br.*?>[ ]*/i" => "</p><p>",
"/<iframe.*?>.*<//iframe>/i" => '',
"/ /i" => ' ',//空格替換掉
"/<p.*?>[ |/x{3000}|/r/n]*/ui" => '<p> ',//替換半角、全角空格,換行符,用 排除寫入數(shù)據(jù)庫時產(chǎn)生的編碼問題
);
$config = array(
//'indent' => TRUE, //是否縮進
'output-html' => TRUE,//是否是輸出xhtml
'show-body-only'=>TRUE,//是否只獲得到body
'wrap' => 0
);
$content = tidy_repair_string($content, $config, 'utf8');//先利用php自帶的tidy類庫修復html標簽,不然替換的時候容易出現(xiàn)各種詭異的情況
$content = trim($content);
foreach ( $replaces as $k => $v ) {
$content = preg_replace ( $k, $v, $content );
}
if(strpos($content,'<p>')>6)//部分內(nèi)容開頭可能缺失<p>標簽
$content = '<p> '.$content;
$content = tidy_repair_string($content, $config, 'utf8');//再修復一次,可以去除html空標簽
$content = trim($content);
return $content;
}
php技術(shù):解析php利用正則表達式解決采集內(nèi)容排版的問題,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。