如果<div>标签内没有数据,则用<tag>标签替换<div>标签内的所有标签,并且在php中使用正则表达式

时间:2016-04-29 11:55:07

标签: php html

实际上,我想删除<div>标记下的所有标记,包括<div>,只有当其中包含<br>标记时才会删除。

例如:

     <div>
          <font face="Arial, Verdana">
             <span style="font-size: 13.3333px;">
               <u>
                fs
               </u>
           </span>
        </font>
     </div>
     <div>
        <br>
     </div>
     <div>
          <font face="Arial, Verdana">
            <span style="font-size: 13.3333px;">
               <u>
                   <br>
                </u>
            </span>
          </font>
     </div>
     <div>
            <font face="Arial, Verdana">
            <span style="font-size: 13.3333px;">
                 <u>
                    <br>
                  </u>
            </span>
            </font>
     </div>
     <div>
          <font face="Arial, Verdana">
              <span style="font-size: 13.3333px;">
                <u>
                   <br>
                 </u>
               </span>
          </font>
     </div>

它的输出应该来了:

     <div>
        <font face="Arial, Verdana">
           <span style="font-size: 13.3333px;">
             <u>
                fs
             </u>
           </span>
        </font>
     </div>
     <br>
     <br>
     <br>

请有人告诉我该怎么做..

1 个答案:

答案 0 :(得分:0)

您可以将DOMDOMXPath一起使用,以获得更好的结果:

/* Init DOMDocument: */
$dom = new DOMDocument();
/* Load HTML: */
libxml_use_internal_errors( True );
$dom->loadHTML( $html, LIBXML_NOBLANKS );
$dom->formatOutput = True;
/* Init DOMXPath: */
$xpath = new DOMXPath( $dom );

/* Search for all <body> <div> children (assuming your <div> are <body> children): */
$nodes = $xpath->query( '//body/div' );

foreach( $nodes as $node )
{
    /* Search for <div> <br> children and - if found it - replace <div> by <br>: */
    $br = $node->getElementsByTagName( 'br' );
    if( $br->length )
    {
        $node->parentNode->replaceChild( $br->item(0), $node );
    }
}

/* Echo modified HTML: */
echo $dom->saveHTML();

结果:

<div>
    <font face="Arial, Verdana">
        <span style="font-size: 13.3333px;">
            <u>
                fs
            </u>
        </span>
    </font>
</div>
<br>
<br>
<br>
<br>