需要帮助preg_replace

时间:2011-06-07 07:33:49

标签: php preg-replace

$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);

OUTPUT(我在这里给出了html格式):

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

我的问题是必须删除所有属性,但属性不属于表。这就是我期待的完全如下( HTML FORMAT ):

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

我应该在上面的正则表达式中修改什么来实现它..

任何帮助都会感恩和感激....

提前致谢...

3 个答案:

答案 0 :(得分:3)

如果你想避免使用正则表达式,因为你真的不应该使用正则表达式来处理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>

答案 1 :(得分:1)

您与目前的注册表非常接近。你需要做一个检查(在这种情况下认为这是一个负面的预测?)

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

reg-ex的第一位做的是检查它是不是以'table'开头,那么它就是你的正则表达式。

答案 2 :(得分:0)

一点hacky解决方案,但有效。 尝试在代码中禁用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 ;

?>