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

时间:2015-07-09 09:47:20

标签: php html ckeditor

我的字符串是这样的。

$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 是'应该替换我的意思是它不会替换任何TAG和属性。

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

1 个答案:

答案 0 :(得分:0)

正如评论中已经建议的那样,你需要使用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;