php把文章的px转换成rem

57 篇文章 1 订阅
50 篇文章 0 订阅

最近项目中写移动端,因为编辑器的内置样式,需要在移动端输出的时候改变字号以及单位,所以需要替换所有包含“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: &quot;Microsoft Yahei&quot;; 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值