$image
可变文本给出了这样的代码(当使用echo
):PHP替换可变
<img src="/image.png" width="100" height="147" alt="" class="some_class" />
width
,height
,src
和class
属性可以是不同的。
我们应该做的:
- 从
$image
- 删除
width
和height
与alt="Poster"
由于更换alt=""
。
$image
可变文本给出了这样的代码(当使用echo
):PHP替换可变
<img src="/image.png" width="100" height="147" alt="" class="some_class" />
width
,height
,src
和class
属性可以是不同的。我们应该做的:
$image
width
和height
与alt="Poster"
由于更换alt=""
。
我会使用正则表达式来做到这一点。
// Replace width="..." and height="..." with nothing
$variable = preg_replace('/(width|height)\s*=\s*"[^"]*"/i', '', $image);
// Replace alt="..." with alt="Poster"
$variable = preg_replace('/alt\s*=\s*"[^"]*"/i', 'alt="Poster"', $variable);
此方法不依赖于属性的顺序,其他答案是哪一个。另请注意,第二个正则表达式将替换alt="<any string here>"
和alt="Poster"
。应该很容易将其更改为仅替换alt=""
。
谢谢你,这个作品! – Happy 2010-07-04 18:16:36
如果属性可以变化,那么使用HTML的最佳选择是使用实际理解HTML的库,如DOM。
$dom = new DOMDocument;
$dom->loadXML($variable);
$dom->documentElement->removeAttribute('width');
$dom->documentElement->removeAttribute('height');
$dom->documentElement->setAttribute('alt', 'poster');
echo $dom->saveXML($dom->documentElement);
输出:
<img src="http://site.com/image.png" alt="poster"/>
谢谢戈登! 1)和高度可以不同。 2)替换alt不起作用 – Happy 2010-07-04 17:57:29
我建议''width =“100”height =“147”alt =“”''因为在你的解决方案之后会有2个alt。 – DrColossos 2010-07-04 17:57:33
$pattern = '/alt="" width="\d+" height="\d+"/i';
$replacement = 'alt="Poster"';
$variable = preg_replace($pattern, $replacement, $variable);
修复与属性的任何命令(Gordon的评论)工作:
$pattern = '/alt=""/i';
$replacement = 'alt="Poster"';
$variable = preg_replace($pattern, $replacement, $variable);
$pattern = '/width="\d+"/i';
$replacement = '';
$variable = preg_replace($pattern, $replacement, $variable);
$pattern = '/height="\d+"/i';
$replacement = '';
$variable = preg_replace($pattern, $replacement, $variable);
也将取代<embed width="x">
这是错误的。我们只需要赶上<img>
标签
是否widht /高度不正确或您为什么要删除它们? – DrColossos 2010-07-04 17:43:22
他们打破了我的JS代码。 – Happy 2010-07-04 17:44:04
为什么你有标记存储在一个变量内? – Dolph 2010-07-04 17:44:34