PHP Replacing Urls With Links – String Function

<?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";?

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.