Skip to content

Instantly share code, notes, and snippets.

@navarr
Last active December 17, 2015 01:09
Show Gist options
  • Save navarr/5526223 to your computer and use it in GitHub Desktop.
Save navarr/5526223 to your computer and use it in GitHub Desktop.
Replace hyperlinks in a textual pattern.
<?php
$description = htmlspecialchars($description);
$matches = array();
preg_match_all('/(\w+:\/\/)?([-\w@:]+\.)+[-\w@:]+(\/\S*)?[^)"\'»”’!?.\s]/', $description, $matches, PREG_SET_ORDER);
$startPos = 0;
foreach ($matches as $match) {
$pattern = $match[0];
if (!isset($match[1]) || !$match[1]) {
$pattern = "http://{$pattern}";
}
$replace = '<a href="' . $pattern . '">' . $pattern . '</a>';
// Find the position of the match so that we replace it and ONLY it.
$i = 0;
do {
$pos = strpos($description, $match[0], $i);
++$i;
} while ($pos < $startPos);
$tempDescription = substr($description, $pos);
$tempDescription = preg_replace('$' . preg_quote($match[0], '$') . '$', $replace, $tempDescription, 1);
$description = substr($description, 0, $pos) . $tempDescription;
$startPos = $pos + strlen($replace);
}
$description = str_replace("\n", "<br />", $description);
return $description;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment