fork download
  1. <?php
  2. //DEBUG START - Remove on production mode
  3. ini_set('display_errors', '1');
  4. //DEBUG END
  5. $html = <<< EOF
  6. <p>This is real content and has no dummy words.</p>
  7. <p>This has words like lorem and ipsum. It should be highlighted.</p>
  8. EOF;
  9.  
  10. $dom = new DOMDocument(); //create new DOMDocument
  11. $dom->loadHTML($html); // load the $html in the new DOMDocument
  12. $xpath = new DOMXPath($dom); // create a new DOMXPath
  13. // loop all <p> tags on the html
  14. foreach($xpath->query("//p") as $paragraph ){ //
  15. //if paragraph text contains lorem ipsum
  16. if(preg_match('/lorem|ipsum/im', $paragraph->textContent)){
  17. //add attribute style="color:red"
  18. $paragraph->setAttribute("style", "color:red");
  19. }
  20. }
  21. //save the new html with the modifications above
  22. $html = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
  23. echo $html;
Success #stdin #stdout 0.03s 52480KB
stdin
Standard input is empty
stdout
<p>This is real content and has no dummy words.</p>
<p style="color:red">This has words like lorem and ipsum. It should be highlighted.</p>