平台使用ectouch做站,MIP出来了一段时间,推广要求把资讯单独提出改造成MIP,所以把资讯列表和资讯详情根据MIP要求进行了改造,但是百度编辑器编辑出来的内容图片需要替换,style也需要提取,我对正则表达式也不熟悉,在网上找了些资源,在此谢谢各位博客君。
资源链接:ectouch之新闻页面MIP化
替换图片使用到的函数:
function replacePicUrl($content = null, $url="") {
$pattern = "/<img(.*?)src=('|\")([^>]*).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = "<mip-img src={$url}$3.$4></mip-img>";
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
有点图片有title,class之类的,可以用下面这个
function replacePicUrl($content = null, $url="") {
//$pattern = "/<img(.*?)src=('|\")([^>]*).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg]|\.png]|\.bmp]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern, $content,$matches);
$full_img = $matches[0];
$full_src = $matches[1];
foreach ($full_img as $k => $v) {
$v1 = str_replace("<img", "<mip-img", $v);
$v1 = str_replace("/>", "></mip-img>", $v1);
$new_path = $url.$full_src[$k];
$v1 = str_replace($full_src[$k], $new_path, $v1);
$content = str_replace($v, $v1, $content);
}
return $content;
}
提取style:
function getStyle($content = null){
preg_match_all("/style=('|\")([^'\"]+)('|\")/",
$content,$matches);
$styles = $matches[0];
$styles_value = $matches[2];
$style_custom = "";
$i = 0;
foreach($styles_value as $key){
$style_custom .= ".class".$i."{".$key."}";
$class_name = 'class="class'.$i.'"';
$replacements = $class_name;
$patterns = $styles[$i];
$content = str_replace($patterns, $replacements, $content);
$i++;
}
$res['style_custom'] = $style_custom;
$res['content'] = $content;
return $res;
}
在controller页面中做替换:
$article = model('Article')->get_article_info($article_id);
$article_content = replacePicUrl($article['content'], "http://www.jxcat.com"); //替换图片
//提取style
$style_res = getStyle($article_content);
$article_content = $style_res['content'];
$style_custom = $style_res['style_custom'];
$article['content'] = $article_content;
$this->assign('article', $article);
$this->assign('style_custom', $style_custom);