我遇到了一些情况。我工作的网站有两个部分,移动和主网站。它们都从同一个数据库/表中获取内容。这是一个博客网站。当管理员使用文本编辑器(CKEditor)创建包含图像的内容时,style
属性将附加到生成的img
标记。所以输出看起来是这样的。
<img alt="some content" src="some location" style="width:520px; height:600px;" />
这在主网站上效果很好,但在移动网站上,图像缩放和拉伸都很差。我有一个图钉脚本可以解决这个问题,但我想要一种在页面加载之前获得src
属性的方法,以及一种删除style
属性的方法。
我使用regex完成了此操作。
$str=$blog_post_column_from_database
$pattern=array ('#'<img alt="(.*?)" src="(.*)" style="(.*?)" /> #' );
$replacement=array ( '<img src="$my_thumbnailer_here.php?src=''2" width="100%" />' );
$a=(string)$str; //converts text to string to avoid code lines from executing
return preg_replace($pattern,$replacement,$a);
请问我做错了什么?。。雷格斯不是我的强项,谢谢。
。。。正如评论中已经建议的那样,您最好使用PHP-DOMDocument:
像这样的东西应该可以做到:
示例:http://3v4l.org/Gv4dp
//get new domdoc instance
$dom=new DOMDocument();
//load your html
$dom->loadHTML($your_html);
//get all images
$imgs = $dom->getElementsByTagName("img");
//iterate over those
foreach($imgs as $img){
//remove style attribute
$img->removeAttribute('style');
//prefix src attribute with scriptname
$img->setAttribute( 'src' , 'thumbnail.php?img=' . $img->getAttribute('src') );
}
//output modified html
echo $dom->saveHTML();
您可能希望删除在将文档保存为html时创建的<doctype>
、<html>
和<body>
元素,方法是将最后一行替换为:
echo preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), '', $dom->saveHTML()));
请参阅保存domdocument 时删除doctype
尝试下一个regexp
$pattern=array ('#<img alt="(.*?)" src="(.*)" style="(.*?)" />#' );
开头有空格,结尾有空格。
为了正确的工作,你应该首先找到所有的img标签,然后更改它
您的regexp将无法工作属性标记alt丢失或属性处于其他顺序时