使用PHP srt_replace替换仅由具有不同长度的前几个字符表示的内容的最佳方法


Best way to use PHP srt_replace to replace content only denoted by the first few chars with varying lengths?

使用srt_replace替换仅由前几个字符表示并且可能具有不同长度的内容的最佳方法是什么?我正试图通过添加媒体来改变WordPress自动嵌入图像的方式。根据图像,我想删除硬编码的宽度值,并将其替换为不同的值。

我可以通过一个循环来处理这个问题,查找字符串width,然后查找下一个空间。然后使用这些起始值和结束值来删除宽度参数和值。但似乎有一种"速记"的方法可以进行这种类型的查找和替换?

如果我知道宽度正好是"321",下面的代码就会起作用,但我如何找到width的任何值并将其替换为width=100%?宽度后面的值可以有任意数量的字符。我想答案会是height,但会有一点变化。

$<a href="http://img.png">
    <img src="http://dev.x.com/wordpress/wp-content/321x205.png" width="100%" height="205">
</a>
$correctwidth = str_replace('width="321" ', 'width="100%" ', $html);

使用Preg_replace执行此操作:

$html = "width='"300'" height='"205'"";
echo preg_replace("#width='"['d+]+'"#", 'width="100%"', $html);

它将返回width="100%"height="205">

此处测试

有时最简单的答案是使用Javascript/jQuery:

 $('img').each(function(){ 
   $(this).removeAttr('width')
   $(this).removeAttr('height');
});

然后是CSS

img {
    width: 100%;
}