我如何删除图像的宽度和高度,而不是框架?代码包括在内


How do I remove image width and height only, not iframes? Code included

我目前在我的wordpress函数文件中使用的代码是这样的:

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)=("|'')'d*(|px)("|'')'s/', "", $html );
   return $html;
}
add_filter( 'the_content', 'remove_width_attribute', 10 );

这里的问题是,它的目标iframe太,所以我将如何重写正则表达式说只有图像?

我会使用非捕获组在其他语句之前搜索img标记,例如

(?:img.*)(width|height ?= ?['"].*['"])

你可以看到它在这里工作:http://regex101.com/r/mI1bD5。

请注意,这在很多简单的情况下会失败(例如,iframeimg标记在同一行),但它应该将您推向正确的方向。

感谢Trevor的建议。这是我修改后的表达式,它做得稍微好一点,但仍然不够好。(?:<img.*){1}((width|height)=['"]'d*['"]) (?:.*'/>|>){1}