2013-04-05 146 views
-1

我試圖找到一種方式來獲得一個字符串標籤和刪除樣式屬性。 之後,我想加上我自己的風格,並注意以下文字.. 例如,我有:找到所有<img>標籤和更改樣式屬性

<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p> 

結束endresult應該是:

<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 100%;" /></p><p>&nbsp;</p><p> 

我已經試過unsuccesfully但正則表達式好像我是太愚蠢瞭解它的功能...

每個幫助將不勝感激!從希臘 吉姆 問候

+0

**不要使用正則表達式來解析HTML **。你不能用正則表達式可靠地解析HTML,你將面臨悲傷和挫折。只要HTML從你的期望改變,你的代碼就會被破壞。有關如何使用已經編寫,測試和調試的PHP模塊正確解析HTML的示例,請參閱http://htmlparsing.com/php。 – 2013-04-05 15:46:56

回答

3

您可以通過正則表達式這樣做:

$str = '<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p>'; 

$newStr = preg_replace('#<img (.+) style="(.+)" />#isU', '<img $1 style="width: 100%" />', $str); 
+0

非常感謝你,對於我遲到的回覆感到抱歉......這是非常有幫助和容易理解的......繼續保持它! – 2013-04-25 09:46:08

1

要刪除高度或一些其他財產:

$string = '<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p' ; 
$pattern = "/height:\s*\d*\s*(px|%);*/" ; 
$new = preg_replace($pattern,"", $string) ; 

echo htmlentities($new) ; 

或移除所有風格的東西,並用自己的替換一些:

$string = '<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p' ; 
$pattern = "/style=[\'\"][^\"|^\']*[\'\"]/" ; 
$own_style = "style='width: 50%'" ; 
$new = preg_replace($pattern, $own_style, $string) ; 

echo htmlentities($new) ; 

一般使用RegExp對HTML標籤有點不好,應該避免,但在某些情況下可能適用。

+0

對不起,我遲到的答覆......你的答案是非常有益的,我用它在另一個問題..對不起,我不能投兩個答案... 據我所知,它不應該被使用,但我不得不更新其containted數據庫這些標籤,並在6000個條目中這樣做看起來像是單向解決方案......完成了這項工作,並學習了更多關於正則表達式的知識!謝謝你的時間! – 2013-04-25 09:48:22