2010-07-04 87 views
0

$image可变文本给出了这样的代码(当使用echo):PHP替换可变

<img src="/image.png" width="100" height="147" alt="" class="some_class" /> 
  • widthheightsrcclass 属性可以是不同的。

我们应该做的:

  1. $image
  2. 删除widthheightalt="Poster"

由于更换alt=""

+0

是否widht /高度不正确或您为什么要删除它们? – DrColossos 2010-07-04 17:43:22

+0

他们打破了我的JS代码。 – Happy 2010-07-04 17:44:04

+0

为什么你有标记存储在一个变量内? – Dolph 2010-07-04 17:44:34

回答

1

我会使用正则表达式来做到这一点。

// 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=""

+0

谢谢你,这个作品! – Happy 2010-07-04 18:16:36

1

如果属性可以变化,那么使用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"/> 
+0

谢谢戈登! 1)和高度可以不同。 2)替换alt不起作用 – Happy 2010-07-04 17:57:29

+0

我建议''width =“100”height =“147”alt =“”''因为在你的解决方案之后会有2个alt。 – DrColossos 2010-07-04 17:57:33

1
$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); 
+0

这里假定属性总是按照这个顺序出现。 – Gordon 2010-07-04 18:04:39

+0

如果属性显示为更多空白,例如, 'alt =“”width =“100”height =“147”'? – Gordon 2010-07-04 18:14:16

0

也将取代<embed width="x">这是错误的。我们只需要赶上<img>标签