日期:2014-05-17 浏览次数:20459 次
<?php /** * @author pqcc <struts.ec@mgail.com> * @date: 2011-06-18 * Description: 给定一个网页内容,提取网页的标题. 提取的标题不包括 seo 关键字. * e.g: 一篇新闻标题的从<title>直接抽取结果为 "大学英语四六级本周六开考 909万人参考_新浪教育_新浪网", * 但我们希望的结果是:"大学英语四六级本周六开考 909万人参考". * 适用范围: 文章最终页标题的提取, 不包括专题页等. */ class TitlePurify{ private $matches_preg = '[-_\s|—]'; function getTitle($contents){/*{{{*/ $preg = "/<title[^>]*>([\w|\t|\r|\W]*?)<\/title>/i"; preg_match($preg, $contents, $matches); if(count($matches)<=1){ return "标题抽取失败"; } $title = $matches[1]; return $this->trimTitle($title, $contents); }/*}}}*/ function trimMeta($contents){/*{{{*/ // 首先去除 <title> 内容, <meta> 内容. $preg = "/<title[^>]*>([\w|\t|\r|\W]*?)<\/title>/i"; $contents = preg_replace($preg, '', $contents); $preg = "/<meta[^>]*>/i"; $contents = preg_replace($preg, '', $contents); return $contents; }/*}}}*/ // 获取长度最长的 item?所处的index. function getMaxIndex($titles){/*{{{*/ $maxItemIndex = 0; $maxLength = 0; $loop = 0; foreach($titles as $item){ if(strlen($item)>$maxLength){ $maxLength = strlen($item); $maxItemIndex = $loop; } $loop++; } return $maxItemIndex; }/*}}}*/ function trim($title, $titles, $contents, $maxItemIndex){/*{{{*/ //@todo : 此处可优化contents // 如果查找成功. result = tempTitle. $tempTitle = $titles[$maxItemIndex]; $result = $tempTitle; $count = count($titles); // while 从当前index 向左进行迭代(直到到达第一个或者匹配失败才中止). $leftIndex = $maxItemIndex-1; while(true && $leftIndex>=0){ // tempTitle+左一个. preg_match("/({$this->matches_preg}+{$tempTitle})/i", $title, $matches); if(count($matches)>1){ // temp 用于匹配失败后,进行回滚. $temp = $titles[$leftIndex] . $matches[1]; $tempTitle = $titles[$leftIndex] . $matches[1]; // 继续拿着 tempTitle 去匹配. preg_match("/$tempTitle/i", $contents, $matches); // 如果查找失败.... if(count($matches)<1){ $tempTitle = $temp; break; }else{ $result = $tempTitle; } }else{ //?正常情况下,?不会出现该情况. break; } $leftIndex--; } // match(current[i-1].[|-].tempTitle), 如果成功, tempTitle = match 成功的值,继续. // while 左边失败后, 从右边开始. $rightIndex = $maxItemIndex+1; while(true && ($rightIndex<=$count)){ preg_match("/({$tempTitle}{$this->matches_preg}+)/i", $title, $matches); if(count($matches)>1){ // temp 用于匹配失败后,进行回滚. $temp = $matches[1] . $titles[$rightIndex]; $tempTitle = $matches[1] . $titles[$rightIndex]; // 继续拿着 tempTitle 去匹配. preg_match("/$tempTitle/i", $contents, $matches); // 如果查找失败.... if(count($matches)<1){ $tempTitle = $temp; break; }