2012-08-01 58 views
-1

排除EM標籤我有這樣的HTML文本:從正則表達式匹配

<strong><em>La congiura della pietra nera</em></strong> 
<p><a href="xxxxx"> 

<img class="alignleft size-medium wp-image-75372" title="mytitle" 

src="my.jpg" alt="" width="247" height="350"></a> 

<strong>Trama:</strong> La storia ruota attorno ad una setta di guerrieri depositaria dei più arcani segreti.</p> 

我需要做的一些字prey_replace,我用這個正則表達式在PHP中:

$mycontent = preg_replace('{'.$words.'(?![^<>]*>)}i','otherwords',$mycontent); 

它工作很好,但我需要排除標籤內的文字,我該如何做?

許多感謝

+2

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2012-08-01 15:21:50

+1

永遠不要用正則表達式解析html。改爲使用[DomDocument](http://php.net/manual/en/class.domdocument.php)。 – Leri 2012-08-01 15:22:41

+0

除了令人困惑的解析和匹配之外,愚蠢的鏈接是相關的。使用規定的正則表達式方法,只能通過高昂的工作才能完成。 (*你*不能)。否則建議使用HTML/DOM遍歷前端。 – mario 2012-08-01 15:32:54

回答

1

參閱以下示例代碼:

<?php 
$foo = '<p><strong>SCHEDA FILM</strong>:<strong> <em>La congiura della pietra nera</em></strong></p>'; 
$bar1 = 'La congiura della pietra nera'; 
$bar2 = 'SCHEDA FILM'; 
echo preg_replace('/(<(?!em\b)(\w+)[^>]*>)'. $bar1 . '(<\/\2>)/', "$1do something$3", $foo); 
//output '<p><strong>SCHEDA FILM</strong>:<strong> <em>La congiura della pietra nera</em></strong></p>' 

echo preg_replace('/(<(?!em\b)(\w+)[^>]*>)'. $bar2 . '(<\/\2>)/', "$1do something$3", $foo); 
//output '<p><strong>do something</strong>:<strong> <em>La congiura della pietra nera</em></strong></p>'  

?>