Skip to content

Instantly share code, notes, and snippets.

@leepowers
Last active December 17, 2015 01:38
Show Gist options
  • Save leepowers/5529546 to your computer and use it in GitHub Desktop.
Save leepowers/5529546 to your computer and use it in GitHub Desktop.
Auto-link URLs in an HTML document that haven't already been linked.
<?php
/**
* Safely auto-link HTML content.
* Doesn't double-link existing content.
* Plus logging features
* @param string $html
* @return string
*/
function safe_autolink($html) {
$doc = new DOMDocument();
$success = $doc->loadHTML($html);
if ($success) {
$xpath = new DOMXpath($doc);
foreach ($xpath->query('//text()') as $text) {
if (!($text->parentNode->tagName == "a")) {
$frag = $doc->createDocumentFragment();
$success = !!$frag->appendXML(preg_replace('#((?:http|https)://\S+)#', '<a href="$1">$1</a>', htmlentities($text->data)));
if ($success) {
$text->parentNode->replaceChild($frag, $text);
} else {
break;
}
}
}
}
if ($success) {
if (version_compare(PHP_VERSION, '5.3.6') >= 0) {
$func_name = "saveHTML";
} else {
$func_name = "saveXML";
}
$autolink_html = $doc->$func_name($xpath->query("//*")->item(0));
$return = $autolink_html;
} else {
$message = "Unable to auto link HTML.";
$exception = new Exception($message);
error_log(sprintf("%s, %s", $message, $exception->getTraceAsString()));
$return = $html;
}
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment