Last active
December 17, 2015 01:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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