2011-06-07 86 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