Last active
December 17, 2015 01:09
-
-
Save navarr/5526223 to your computer and use it in GitHub Desktop.
Replace hyperlinks in a textual pattern.
This file contains hidden or 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 | |
$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