0

I have this html as just example

this is some html code, and this is <a href="domain.com" title="html">html</a>

this is image <img src="any url with html word" alt="html" />

<iframe src="html"></iframe>

<script type="text/javascript">
    var html = "any thing here";
    var x = "this is html"
</script>

I want any way to replace all html word with <a href="domain.com/search/html">html</a>

As we see it may be in html tag attribute and we must exclude all these chance to replace and just replace this word if it plain text in span or p or div

I tried all dom ways to do that and no way

$dom = new DOMDocument();
$dom->loadHTML($str);
$xpath = new DOMXPath($dom);
$query_entries = $xpath->evaluate("(//div | //span | //p)[not(ancestor::a)]/text()");

foreach($query_entries as $element){
    if($element instanceof DOMText){
        $element->nodeValue = str_replace('html','<a href="domain.com/search/html">html</a>',$element->nodeValue);
    }
}

When I replace the nodeValue with a html it escape it and if I try to decode it it make errors in js codes

Any regex solution?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Mostafa Elkady
  • 5,645
  • 10
  • 45
  • 69
  • 4
    [Don't use regular expressions.](http://stackoverflow.com/a/1732454/1679849) Use a DOM parser instead. – r3mainer Jan 03 '16 at 23:22
  • 2
    Just to be clear: you really have a literal word `html` to replace? Or is that just a sample? – Wiktor Stribiżew Jan 03 '16 at 23:24
  • Have a look at [my demo](http://ideone.com/Jls85M). Also, there other ways, have a look at [this thread](http://stackoverflow.com/questions/31285116/simple-html-dom-replace-all-occurrences-of-a-certain-word-without-affecting/31286023). – Wiktor Stribiżew Jan 03 '16 at 23:55

0 Answers0