2011-06-07 85 views
0
$text = '<p width="50px;" style="padding:0px;"><strong style="padding:0;margin:0;">hello</strong></p><table style="text-align:center"></table>'; 

$text_2 = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $text); 

輸出(I給這裏的HTML格式):需要用的preg_replace幫助

<p> 
<strong>hello</strong> 
</p> 
<table></table> 

我的問題是所有屬性必須被刪除,但不是屬性屬於表。這就是我期待的了把酷似以下(HTML格式):

<p> 
<strong>hello</strong> 
</p> 
<table style="text-align:center"></table> 

我應該需要在上述正則表達式來實現它來修改什麼..

任何幫助會感激和感激....

在此先感謝...

+0

可能重複[php:我如何從html標籤中刪除屬性?](http://stackoverflow.com/questions/770219/php-how-can-i-remove-attributes-from-an-html-tag) – kapa 2011-06-07 09:04:42

回答

1

你非常接近與您當前的REG-EX。你需要做的檢查(認爲它是一個負前瞻在這種情況下?)

<(?!table)([a-z][a-z0-9]*)[^>]*?(\/?)>

什麼REG-EX的是第一位正在做的是檢查它不以「表」啓動,那麼這是你的正則表達式。

+0

謝謝迪基...你讓我形成:-(到:-)通過你的回答....謝謝朋友......我還有一個小小的懷疑。如果我需要在NOT條件中添加兩個或更多標籤,如表格,我應該怎麼做?... – Fero 2011-06-07 09:05:04

+0

您可以將自己的標籤添加到預覽中,例如'(?!table | div | othertag)' – 2011-06-07 09:20:47

+0

非常感謝你的直接響應Dickie .. :-) – Fero 2011-06-07 09:26:33

0

位哈克解決方案,但作品。 嘗試在代碼中禁用TABLE標記一段時間,然後再次啓用它們。 它會工作。

看到:http://codepad.org/nevLWMq8

<?php 

$text = '<p width="50px;" style="padding:0px;"><strong style="padding:0;margin:0;">hello</strong></p><table style="text-align:center"></table>'; 

/* temporary change table tags with something not occuring in your HTML */ 
$textTemp = str_replace(array("<table","/table>"),array('###','+++'),$text); 


$text_2 = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $textTemp); 



echo "\n\n"; 
/* restore back the table tags */ 

$finalText = str_replace(array("###","+++"),array("<table","/table>"),$text_2); 
echo $finalText ; 

?> 
3

如果你想避免使用正則表達式,因爲你真的souldn't使用正則表達式對XML/HTML結構工作,嘗試:

<?php 
$text = '<p width="50px;" style="padding:0px;"><strong style="padding:0;margin:0;">hello</strong></p><table style="text-align:center"></table>'; 

$dom = new DOMDocument; 
$dom->formatOutput = true; 
$dom->loadHtml($text); 

$xpath = new DOMXpath($dom); 
foreach ($xpath->query('//*[not(name()="table")]/@*') as $attrNode) { 
    $attrNode->ownerElement->removeAttributeNode($attrNode); 
} 

$output = array(); 
foreach ($xpath->query('//body/*') as $childNode) { 
    $output[] = $dom->saveXml($childNode, LIBXML_NOEMPTYTAG); 
} 

echo implode("\n", $output); 

輸出:中

<p> 
    <strong>hello</strong> 
</p> 
<table style="text-align:center"></table> 
+0

感謝您的建議「不能使用正則表達式來處理XML/HTML結構」。但就我而言,只是以PDF格式查看內容。這就是我爲之而去的...... – Fero 2011-06-07 09:06:22