对字符串进行去重的核心方法如下Common.cls.php:
class Common {
/**
* 获取新行程中的文字
* 将$title中的img标签去除
* @param $title
* @return Ambigous <boolean, multitype:>
*/
public static function getSubTitle($title){
//应该不会出现一天换5次交通的情况吧
$pattern = '/<img (.*?)[<(.*?)>]{0,5}>/';
preg_match_all($pattern, $title, $matches );
if(isset($matches[0]) && !empty($matches[0])){
$match_info = $matches[0];
foreach ($match_info as $str){
$title = str_replace($str, '::', $title) ;
}
$title = self::removeSpecial($title);
$title_arr = explode('::',$title);
}
if(isset($title_arr) && !empty($title_arr)){
$result = $title_arr;
}else{
$title = self::removeSpecial($title);
$result = array($title);
}
return $result;
}
/**
* 过滤特殊字符,去除Html标签
* @param $title
* @return string
*/
private static function removeSpecial($title){
$title_tmp = $title;
//过滤title中的特殊字符
$html_info = array("<br>","\r\n","\n"," ");
foreach ($html_info as $hi ){
$title_tmp = str_replace($hi, '', $title_tmp);
}
//去除标题中的(...)
$title_tmp = preg_replace('/(.*?)/', '', $title_tmp);
//过滤html标签
$title_tmp = strip_tags($title_tmp);
return trim($title_tmp);
}
/**
* 获取当前时间
* @return number
*/
public static function getMicroTime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
}
下面是对其的测试应用test.php
require_once 'Common.cls.php';
$data = '[{"day":"1","title":"南京<img src=\"http://img3.tuniucdn.com/site/images/index/logo_v4.gif\">北京","summary":["难道是匹配行程里的。九寨沟 天坛<br>"]},{"day":"2","title":"北京<img src=\"http://img3.tuniucdn.com/site/images/index/logo_v4.gif\">东京","summary":["一线天 三亚<br>"]},{"day":"3","title":"东京<img src=\"http://img3.tuniucdn.com/site/images/index/logo_v4.gif\">西京","summary":["黄石公园 博物馆<br>"]}]' ;
$info = json_decode($data,true);
$title_arr = array();
foreach ($info as $route_info){
$title_tmp = Common::getSubTitle($route_info['title']);
$title_tmp_end = end($title_tmp) ;
foreach ($title_tmp as $t){
if(count($title_arr) == 0){
$title_arr[] = $t;
continue;
}
if($t != $title_tmp_end){
$title_arr[] = $t;
}
}
}
$result = implode('>>', $title_arr);
header('Content-type: text/html; charset=utf-8');
echo $result;