繁体   English   中英

在 preg_replace 方面需要帮助

[英]Need help with 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);

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

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

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

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

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

任何帮助将不胜感激和感激....

提前致谢...

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

Output

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

您与当前的正则表达式非常接近。 您需要进行检查(认为在这种情况下这是一个负面的前瞻性?)

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

reg-ex 的第一部分所做的是检查它是否不是以“table”开头的,那么它就是你的正则表达式。

有点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 ;

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM