最近项目中写移动端,因为编辑器的内置样式,需要在移动端输出的时候改变字号以及单位,所以需要替换所有包含“px”,参考原文: http://www.thinkphp.cn/topic/59967.html 我自己稍微做了一些修改,代码如下:
/*
* 替换移动端单位px --- rem
* $content 文章内容
* $fontsize 手动指定字号
*/
public function format_content($content,$fontsize){
if( empty($content) )
{
return $content;
}
if( preg_match_all('/\d+px;/is',$content,$matchs) )
{
$count=count( $matchs[0] );
for ($i=0;$i<$count;$i++)
{
$replace=preg_replace('/px;/','',$matchs[0][$i])*0.01.'rem;';
$content=str_replace($matchs[0][$i],$replace,$content);
}
//新增 部分字号转换后太小,这里赋予一个固定的最小字号
//$content = "color: rgb(51, 51, 51); font-family: "Microsoft Yahei"; text-indent: 0.36rem; background-color: rgb(255, 255, 255); font-size: 0.2rem;";
// 正则 /font-size:\s\d.\d*+rem/ ==> font-size: 0.2rem
preg_match_all('/font-size:\s\d.\d*/',$content,$matchs);
$str = $matchs[0][0]; //font-size: 0.2rem; 获取到的值
$arr = explode(' ',$matchs[0][0]);
if($arr[1] < 0.26){ //如果编辑器中的字号太小,则手动匹配字号
$replace = 'font-size: '.$fontsize;
$content = str_replace($str,$replace,$content); //替换 font-size: 0.2;
}
}
return $content;
}