fork download
  1. <?php
  2. $_SERVER['HTTP_HOST'] = "ideone.com"; // fake it, we don't need it!
  3. $output = '<a href="https://google.com">External Link</a> | <a href="#anchor">Anchor</a> | <a href="http://i...content-available-to-author-only...e.com">Internal Link</a>';
  4.  
  5. // start
  6. $doc = new DOMDocument();
  7. $doc->preserveWhiteSpace = false;
  8.  
  9. $doc->loadHTML($output);
  10.  
  11. $links = $doc->getElementsByTagName('a');
  12. foreach ($links as $item) {
  13. $href = parse_url($item->getAttribute('href'), PHP_URL_HOST);
  14. if (!empty($href) && $href != $_SERVER['HTTP_HOST']){
  15. $item->setAttribute('target','_blank');
  16. }
  17. }
  18.  
  19.  
  20. $output = $doc->saveHTML();
  21.  
  22.  
  23. echo($output);
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://w...content-available-to-author-only...3.org/TR/REC-html40/loose.dtd">
<html><body><a href="https://google.com" target="_blank">External Link</a> | <a href="#anchor">Anchor</a> | <a href="http://i...content-available-to-author-only...e.com">Internal Link</a></body></html>