如何在PHP中通过特殊标记将html分隔为2个文件


How to separate html to 2 file by special tag in PHP

我试着用我指向的标签把一个html文件分成两个。

例子
<html>
   <head>
       <title>html title</title>
   </head>
   <body>
       <h1>hello title</h1>
       <p class="p2">
         <span>here is some txt</span>
       </p>
       <p class="p2">
         hello test, <a id="chp"></a>here is some txt
       </p>
   </body>
</html>

如果我定义分隔符为。这两个文件应该如下

文件1:

<html>
   <head>
       <title>html title</title>
   </head>
   <body>
       <h1>hello title</h1>
       <p class="p2">
         <span>here is some txt</span>
       </p>
       <p class="p2">
         hello test,
       </p>
   </body>
</html>
文件2:

<html>
   <head>
       <title>html title</title>
   </head>
   <body>
       <h1>hello title</h1>
       <p class="p2">
         <span>here is some txt</span>
       </p>
       <p class="p2">
         <a id="chp"></a>here is some txt
       </p>
   </body>
</html>

谁能告诉我如何实现这个?

谢谢

如果使用SimpleXML库加载html,则可以遍历html对象以检查每个元素。如果在移动到下一个元素之前检查每个元素的子节点,对于标记为a并且具有属性id = 'chp'的元素,您可以中断复制并删除该元素之后的内容(直到父元素的末尾),克隆SimpleXML对象,然后用从前SimpleXML对象复制的内容替换整个元素。