剪切HTML标签并再次包装HTML标签Part / 2 [复制]

This question already has an answer here:

its possible to map the cascade of tags in each child-tag of current parent tag, like this

FROM:

<p>
     string
    <b>
      bold
        <em>italic string</em>
      also(bold)
    </b>
 </p>

TO: convert to this String

  <p>
    string
  </p>

        <b p><!--------------------------------------- insert -->
          bold
        </b p><!--------------------------------------- insert -->

            <em b p>italic string</em b p><!----------- insert -->

        <b p> <!--------------------------------------- insert -->
          also(bold)
        </b p><!--------------------------------------- insert -->

   <p>
   </p>

the base question (Part 1) was answered by jerry Cut HTML Tags and wrap HTML tags again Part/1

i think regex is my friend, also in this case :)

</div>

Solution

source

$page = '
<u>
str
<b>
bold
<em>
ital
<strike>
ic stri
</strike>
ng
</em>
also(bold)
</b>
</u>
<u>
str
<b>
bold
also(bold)
</b>
</u>
';

Init vars ...

$o = 'open';
$c = 'close';
$n = 'node';

$tag = null;
$tagName = null;
$addNode = null;
$strTmp = null;

grep each lines ...

foreach(preg_split("/((?
)|(
?))/", $page) as $line){
    $lines[] = $line;
}

replace logic ...

for($i=0;$i<count($lines);$i++) {

    $line = $lines[$i];
    preg_match ('/<([^\/<]*?)>/' , $line, $open);
    preg_match ('/<(\/[^<]*?)>/' , $line, $close);

    $str = ""; 

    if($tag == $o ){

        if($addNode) {
            $str .= "#".$addNode."#";
        }
        $str .= $line;

        preg_match ('/<(\/[^<]*?)>/' , $lines[$i+1], $m);
        if(!strpos(@$m[1], $tagName)) {
            $addNode .= $tagName." ";
        }
    }

    if($tag == $c ){
        $str .= $line;
        $addNode = null;
    }

    if($tag == $n ){
        $str .= $line;
    }

    //$line = $addNode.$line;

    if(count($open)>0){$tag = $o; $tagName = $open[1];}
    if(count($close)>0){$tag = $c;}
    if(count($open)<1 && count($close)<1 ){$tag = $n;}

    $strTmp .= $str;

}

print ...

echo $strTmp = preg_replace('(<([\w]+)>#([^#]*)#)' , "<$1 $2>", $strTmp);