2010-07-04 88 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>標籤