Replacing URLs with Links
<?php
$hostRegex = "([a-z\d][-a-z\d]*[a-z\d]\.)*[a-z][-a-z\d]*[a-z]";
$portRegex = "(:\d{1,})?";
$pathRegex = "(\/[^?<>#\"\s]+)?";
$queryRegex = "(\?[^<>#\"\s]+)?";
$urlRegex = "/(?:(?<=^)|(?<=\s))((ht|f)tps?:\/\/" . $hostRegex . $portRegex . $pathRegex . $queryRegex . ")/";
$str = "http://home.example.com.";
$str2 = "http://home.example.com:8181/index.php";
echo $urlRegex . "\n";
$sample1 = preg_replace($urlRegex, "<a href=\"\\1\">\\1</a>", $str);
$sample2 = preg_replace($urlRegex, "<a href=\"\\1\">\\1</a>", $str2);
echo $sample1 . "\n";
echo $sample2 . "\n";
?
Related examples in the same category