How to replace plain URLs with links in JavaScript or PHP?

Hello Friends

If you want to convert plain text in to URLs in JavaScript or PHP. This is good solution for you.

In PHP :

public function makeLinks($str)
{
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    $urls = array();
    $urlsToReplace = array();
    if(preg_match_all($reg_exUrl, $str, $urls)) {
        $numOfMatches = count($urls[0]);
        $numOfUrlsToReplace = 0;
        for($i=0; $i<$numOfMatches; $i++) {
            $alreadyAdded = false;
            $numOfUrlsToReplace = count($urlsToReplace);
            for($j=0; $j<$numOfUrlsToReplace; $j++) {
                if($urlsToReplace[$j] == $urls[0][$i]) {
                    $alreadyAdded = true;
                }
            }
            if(!$alreadyAdded) {
                array_push($urlsToReplace, $urls[0][$i]);
            }
        }
        $numOfUrlsToReplace = count($urlsToReplace);
        for($i=0; $i<$numOfUrlsToReplace; $i++) {
            $str = str_replace($urlsToReplace[$i], "<a target='_balnk' href=\"".$urlsToReplace[$i]."\">".$urlsToReplace[$i]."</a> ", $str);
        }
        return $str;
    } else {
        return $str;
    }
}

In JavaScript

function makeLinks(text) {
 var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
 return text.replace(exp,"<a target='_blank' href='$1'>$1</a>");
}

Hope it helps.

4 thoughts on “How to replace plain URLs with links in JavaScript or PHP?

  1. function makeLinks($text)
    {
    $text = preg_replace(‘/(((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_+.~#?&\/\/=]+)/i’, ‘\1‘, $text);
    $text = preg_replace(‘/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&\/\/=]+)/i’, ‘\1\2‘, $text);
    $text = preg_replace(‘/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})/i’, ‘\1‘, $text);

    return $text;
    }

  2. function makeClickableLinks($text)
    {
    $text = preg_replace(‘/(((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_+.~#?&\/\/=]+)/i’, ‘\1‘, $text);
    $text = preg_replace(‘/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&\/\/=]+)/i’, ‘\1\2‘, $text);
    $text = preg_replace(‘/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})/i’, ‘\1‘, $text);

    return $text;
    }

Leave a comment