Php正则表达式替换元素


Php regex replace elements

im试图更改PHP中的html元素。

首先,将textarea替换为h1。需要更换的东西看起来像这样:

<textarea class="head" id="hd_x">Random headline</textarea>

我想改成这个:

<h1 class="head" id="hd_x">Random headline</h1>

随机标题可以是-狗喜欢猫,猫不喜欢狗。

id中的X可以是数字-hd_1、hd_2等等(但我认为它不需要触摸,所以可以忽略)。

第二个是需要用p替换文本区域。原始看起来像这样:

<textarea class="text" id="txt_x">Random text</textarea>

我想改成这个:

<p class="text" id="txt_x">Random text</h1>

这里的随机文本和X的工作原理与第一个相同

如果你能弄清楚我想做什么,这是可能的,而且很短,那么如果你帮我只做H1部分,那就太好了。我想我可以算出<p>(第二部分)。

我试着用str_replace来做,但问题是它总是用</h1></p> 代替</textarea>

谢谢


我的想法是,我需要两个单独的preg_replace。其中一个识别这一部分:

<textarea class="head" 

知道它需要替换为:

<h1 class="head"  

主题跳过此部分:

id="hd_x">Random headline

然后它preg_replace再次识别这个:

</textarea>

并替换为:

</h1>

尽量缩短。通过此查找(???是应该忽略并保持不变的部分):

<textarea class="head" ??????????????????</textarea>

并替换为(????是未受影响的零件):

class="head"我认为是必要的,因为preg_replace模式是这样计算的,它需要用h1代替,而不是用p代替。

您不应该使用RegEx来更改HTML元素。DOM识别结构,xpath使您可以轻松地执行所需操作:

$html = <<<'HTML'
<html>
  <body>
    <textarea class="head" id="hd_x">Random headline</textarea>
    <textarea class="text" id="hd_x">Random headline</textarea>
  </body>
</html>
HTML;
$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXpath($dom);
$names = array(
  'head' => 'h1', 'text' => 'p'
);
$nodes = $xpath->evaluate('//textarea[@class="head" or @class="text"]');
foreach ($nodes as $node) {
  // create the new node depending on the class attribute
  $type = $node->getAttribute('class');
  $newNode = $dom->createElement($names[$type]);
  // fetch all attributes of the current node
  $attributes = $xpath->evaluate('@*', $node);
  // and append them to the new node
  foreach ($attributes as $attribute) {
    $newNode->appendChild($attribute);
  }
  // replace the current node with the new node
  $node->parentNode->replaceChild($newNode, $node);
}
var_dump($dom->saveHtml());