2010-08-26 123 views
0

正則表達式是不是我的專長,可能真的幫助做匹配和更換如下:需要一個正則表達式解析HTML標籤

在一個HTML文件,我有這樣的HTML的很多實例:

<font class=font8>text text text</font> 

字體標籤可以在單個單詞或多個單詞中包含不同的內容,包含空格和數字。

我需要找到的這所有實例,並替換爲:

<span class="bold">(text that was there)</span> 

感謝 詹姆斯

PS:從字,它生成的HTML爲什麼如此糟糕:O)

+9

請參閱http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Robert 2010-08-26 17:13:49

+0

可能重複[如何解析和處理與PHP的HTML?](http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) – PeeHaa 2012-01-16 19:57:20

回答

4

使用getElementsByTagName('font')DOMDocument::loadHTML方法並遍歷基於->length的節點列表,然後createElement('span')setAttribute爲類名稱值粗體,請執行replaceChild來替換它。

參考的DOM:http://php.net/manual/en/book.dom.php

+0

我似乎無法弄清楚如何用這個。我能得到儘可能的replaceChild但它不工作... 爲($ I = 0; $ I < $dom->的getElementsByTagName( '字型') - >長度; $ I ++){ \t $爲newElement = $ dom- >的createElement( '跨度'); \t $ dom-> replaceChild($ dom-> getElementsByTagName('font') - > item($ i),$ newElement); } – jodm 2010-08-26 19:51:06