我想寫一個簡單的函數來關閉使用PHP preg_replace丟失的HTML標記。幫助PHP正則表達式使用背後的負面看
我認爲這將是相對直接的,但由於某種原因,它沒有。
什麼基本上,我試圖做的是密切以下行中缺少標籤:
<tr>
<th class="ProfileIndent0">
<p>Global pharmaceuticals</p>
<td>197.2</td>
<td>94</td>
</tr>
我一直在服用的方法是使用一個負的外觀後面找到打開是TD標籤而不是在打開的th標籤和正確關閉的th標籤之前。
例如:
$text = preg_replace('!<th(\s\S*){0,1}?>(.*)((?<!<\/th>)[\s]*<td>)!U','<th$1>$2</th>',$text);
我寫的正則表達式模式無數不同的方法都無濟於事。問題在於,我似乎無法完全匹配前一個缺失/前一個開放td,而是似乎與幾個開放td標籤匹配。
下面是完整的輸入文本:
<CO_TEXT text_type_id="6">
<TEXT_DATA><![CDATA[<table class="ProfileChart"> <tr> <th class="TableHead" colspan="21">2008 Sales</th> </tr>
<tr> <th class="ProfileIndent0"></th> <th class="ProfileHead">$ mil.</th> <th class="ProfileHead">% of total</th> </tr>
<tr> <th class="ProfileIndent0"> <p>Global pharmaceuticals</p> <td>197.2</td> <td>94</td> </tr>
<tr> <th class="ProfileIndent0">Impax pharmaceuticals</th> <td>12.9</td> <td>6</td> </tr>
<tr> <th class="ProfileTotal">Total</th> <td class="ProfileDataTotal">210.1</td> <td class="ProfileDataTotal">100</td> </tr> </table><h3>Selected Generic Products</h3><ul class="prodoplist"><li>Anagrelide hydrochloride (generic Agrylin, thrombocytosis)</li><li>Bupropion hydr ochloride (generic Wellbutrin SR, depression)</li><li>Colestipol hydrochloride (generic Colestid, high cholesterol)</li><li>Dantrolene sodium (generic Dantrium, spasticity)</li><li>Metformin Hcl (generic Glucophage XR, diabetes)</li><li>Nadolol/Bendroflumethiazide (generic Corzide, hypertension)</li
><li>Oxybutynin chloride (generic Ditropan XL, urinary incontinence, with Teva)</li><li>Oxycodone hydrochloride (generic OxyContin controlled release, pain)</li><li>Pilocarpine hydrochlorine (generic Salagen, dry mouth caused by radiation therapy)</li></ul>]]></TEXT_DATA> </CO_TEXT>
有什麼用PHP負面看屁股,我是不知道的,或有我只是打不上合適的匹配模式怎麼回事?
任何幫助將不勝感激。
感謝, 約翰
嗨! (對不起,這不是一個安慰;只是一個想法;也許它會幫助你認爲可能有其他方法來做到這一點)看看你的正則表達式,只有一件事情發生在我腦海裏:正則表達式可能不是「正確的工具「,你正在嘗試做什麼......這已經是一個很難閱讀的正則表達式,我不認爲它必須變得能夠處理任何種類的混淆僞-HTML可能會餵它... – 2009-08-03 22:44:52
Pascal,是的 - 我知道你在說什麼。在過去的幾天裏,我的頭撞牆後,我認爲有更好的方法來解決這個問題。特別是,在源頭捕捉不良HTML - 而不是顯示結束。 – John 2009-08-04 14:59:28