0

My string is like this.

$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";

If i replace roh only 'seeing roh is' should be replace i mean it will not replace any TAG and attributes.

There can be any HTML tag. This is Ckeditor data. It should replace only HTML parsed data.

bhupendra
  • 43
  • 3
  • 10
  • Use the [DOM](http://php.net/manual/fr/book.dom.php) library and hit only the [innerHTML](http://stackoverflow.com/questions/2087103/how-to-get-innerhtml-of-domnode) – Answers_Seeker Jul 09 '15 at 09:56

1 Answers1

0

As it was already suggested in the comment, you need to use the DOMDocument php class but also DOMXPath.
Get the wholeText and replace your string. The reconstruct the HTML.

See example:

<?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;
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42