• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

解析php利用正则表达式解决采集内容排版的问题_PHP

php 搞代码 4年前 (2022-01-25) 12次浏览 已收录 0个评论

正则表达式

做采集经常遇到的问题是内容排版问题,用了一些时间写了个用正则替换html标签和样式的函数,共享下。
复制代码 代码如下:
/**
* 格式化内容
* @param string $content 内容最好统一用utf-8编码
* @return string
* !本函数需要开启tidy扩展
*/
function removeFormat($content) {
$replaces = array (
“//i” => ”,
“/<\/font>/i” => ”,
“//i” => ”,
“/<\/strong>/i” => ”,
“//i” => ”,
“/<\/span>/i” => ”,
“/

/i” => “

“,
“/<\/div>/i” => “

“,
“/<!—ecms *–>/i”=>”,
/* “/

/i” => ”,//遇到有表格的内容就不要启用
“/<\/table>/i” => ”,
“/

/i” => ”,
“/<\/tbody>/i” => ”,
“/

/i” => ‘

‘,
“/<\/tr>/i” => ‘

‘,
“/

/i” => ”, */
“/style=.+?[‘|\”]/i” => ”,
“/class=.+?[‘|\”]/i” => ”,
“/id=.+?[‘|\”]/i”=>”,
“/lang=.+?[‘|\”]/i”=>”,
//”/width=.+?[‘|\”]/i”=>”,//不好控制注释掉
//”/height=.+?[‘|\”]/i”=>”,
“/border=.+?[‘|\”]/i”=>”,
“/face=.+?[‘|\”]/i”=>”,
“/
[ ]*/i” => “

“,
“/<iframe.*?>.*<\/iframe>/i” => ”,
“/ /i” => ‘ ‘,//空格替换掉
“/

[ |\x9来源gaodai#ma#com搞@代~码$网搞gaodaima代码{3000}|\r\n]*/ui” => ‘

‘,//替换半角、全角空格,换行符,用 排除写入数据库时产生的编码问题

);
$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标签,不然替换的时候容易出现各种诡异的情况
$content = trim($content);
foreach ( $replaces as $k => $v ) {
$content = preg_replace ( $k, $v, $content );
}

if(strpos($content,’

‘)>6)//部分内容开头可能缺失

标签
$content = ‘

‘.$content;

$content = tidy_repair_string($content, $config, ‘utf8’);//再修复一次,可以去除html空标签
$content = trim($content);
return $content;
}


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:解析php利用正则表达式解决采集内容排版的问题_PHP

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址