$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