因工作需要,需要采集html,并把html内容保存到数据库中。为了避免影响使用,宽高样式需要删除。例如图片和p中的width, height等。
不过采集到的html中,样式的写法各有不同,例如大小写,中间有空格等。
因此使用php正则编写了下面这个方法,对这些奇葩的样式进行过滤。
代码如下:
<?php/**
 * 清除宽高样式
 * @param  String $content 内容
 * @return String
 */function clear_wh($content){
    $config = array('width', 'height');    foreach($config as $v){        $content = preg_replace('/'.$v.'\s*=\s*\d+\s*/i', '', $content);        $content = preg_replace('/'.$v.'\s*=\s*.+?["\']/i', '', $content);        $content = preg_replace('/'.$v.'\s*:\s*\d+\s*px\s*;?/i', '', $content);
    }    return $content;
}?>演示:
<?php$html = <<<HTML
<p style="text-align:center" width="500" height="300">
    <p style="Width : 100px ; Height: 100 px;">
        <img src="/images/test.jpg" width=400 height = 200>
        <p style="float:left; width: 100px; height : 200 px;"></p>
    </p>
    <p style="width :   100 px ;height: 100px">
        <img src="/images/test.jpg" width=400 height = 200>
    </p>
</p>
HTML;echo '<xmp>';echo '原内容:'.PHP_EOL;echo $html.PHP_EOL.PHP_EOL;echo '过滤后内容:'.PHP_EOL;echo clear_wh($html);echo '</xmp>';
?>输出:
立即学习“PHP免费学习笔记(深入)”;
原内容:<p style="text-align:center" width="500" height="300">
    <p style="Width : 100px ; Height: 100 px;">
        <img src="/images/test.jpg" width=400 height = 200>
        <p style="float:left; width: 100px; height : 200 px;"></p>
    </p>
    <p style="width :   100 px ;height: 100px">
        <img src="/images/test.jpg" width=400 height = 200>
    </p></p>过滤后内容:<p style="text-align:center"  >
    <p style=" ">
        <img src="/images/test.jpg" >
        <p style="float:left;  "></p>
    </p>
    <p >
        <img src="/images/test.jpg" >
    </p></p>本篇讲解php使用正则去除宽高样式的方法,更多相关内容请关注php中文网。
相关推荐:
以上就是关于php使用正则去除宽高样式的方法的详细内容,更多请关注php中文网其它相关文章!
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号