2013-11-20 23 views
0

我有一些情況。這個網站有兩部分是手機和主要網站。他們都從同一個數據庫/表中獲取內容。它是一個博客網站。當管理員使用文本編輯器(CKEditor)創建包含圖像的內容時,style屬性將附加到生成的img標記上。所以輸出看起來像這樣。PHP中失敗的正則表達式語法

<img alt="some content" src="some location" style="width:520px; height:600px;" /> 

這對主要網站非常有效,但在移動網站上圖像縮放比較差。 我有一個縮略圖腳本,可以解決這個問題,但我想要一種方式來獲得頁面加載前的src屬性和刪除style屬性的方法。

我使用正則表達式。

$str=$blog_post_column_from_database 

$pattern=array ('#\<img alt="(.*?)" src="(.*)" style="(.*?)" /> #'); 

$replacement=array ('<img src="$my_thumbnailer_here.php?src=\\2" width="100%" />'); 

$a=(string)$str; //converts text to string to avoid code lines from executing 

return preg_replace($pattern,$replacement,$a); 

請問我做錯了什麼?..正則表達式不是我的強項謝謝。

+5

正則表達式。改爲使用[DOM](http://php.net/dom)。 –

+0

http://stackoverflow.com/questions/5517255/remove-style-attribute-from-html-tags –

+0

@MarkResølved感謝您的鏈接..它效果很好,但不給我一個選項來放置我的thumnbail變量.. .Dont真的知道如何破解它... :) – jcobhams

回答

1

...作爲評論已經建議,你會使用PHP的DOMDocument會更好:

像這樣的東西應該做的伎倆:

例如:http://3v4l.org/Gv4dp

//get new domdoc instance 
$dom=new DOMDocument(); 

//load your html 
$dom->loadHTML($your_html); 

//get all images 
$imgs = $dom->getElementsByTagName("img"); 

//iterate over those 
foreach($imgs as $img){ 
    //remove style attribute 
    $img->removeAttribute('style'); 
    //prefix src attribute with scriptname 
    $img->setAttribute('src' , 'thumbnail.php?img=' . $img->getAttribute('src')); 
} 

//output modified html 
echo $dom->saveHTML(); 

您可能需要刪除<doctype>,<html><body>元素,這些元素是通過將最後一行替換爲html將文檔保存爲html時創建的:

echo preg_replace('/^<!DOCTYPE.+?>/', '', str_replace(array('<html>', '</html>', '<body>', '</body>'), '', $dom->saveHTML())); 

看到removing doctype while saving domdocument

+0

感謝您的回答@Mark ...它工作得很好。 – jcobhams

0

嘗試下一個正則表達式

$pattern=array ('#<img alt="(.*?)" src="(.*)" style="(.*?)" />#'); 

有被刪除/從開始和結束空間。

而對於正確的工作,你應該先找到所有的img標籤,然後改變它。

你的正則表達式是行不通的屬性標記ALT被遺漏或屬性時,在其他訂單應避免對HTML