查找并替换php中的DOM html字符串


find and replace DOM html string in php

我的字符串是这样的

$html_string = "This is a book and <img src='roh.png' /> and i am seeing roh is going to src.<br />how about you roho. <span class='jums'>this is jums</span> and he is a good <strong>body</strong>. He is so strong";

如果我只替换roh '看到roh is'应该被替换,我的意思是它不会替换任何TAG和属性。

可以有任何HTML标签。这是Ckeditor数据。它应该只替换HTML解析过的数据

正如在评论中已经建议的那样,您需要使用DOMDocument php类,但也需要使用DOMXPath。
找到wholeText并替换你的字符串。重建HTML。

看到的例子:

<?php
$html = "This is a book and <img src='roh.png' /> and i am seeing roh is going to src.<br />how about you roho. <span class='jums'>this is jums</span> and he is a good <strong>body</strong>. He is so strong";
$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXPath($dom);
foreach($xpath->query('//text()') as $node)
{
    $replaced = str_ireplace('roh', 'NewROH', $node->wholeText);
    $newNode  = $dom->createDocumentFragment();
    $newNode->appendXML($replaced);
    $node->parentNode->replaceChild($newNode, $node);
}
$replacedHTML = $dom->saveXML($xpath->query('//body')->item(0));
print $replacedHTML;