StrongJoshua
StrongJoshua

Reputation: 995

PHP: Detect if string is a hyperlink and make it clickable

In most chat applications when a user inputs a hyperlink, it automatically becomes clickable in the chat window. How do I replicate this behavior using PHP/JavaScript/JQuery?

Essentially my idea of making it work is testing the chat message string for hyperlinks and encasing them in <a href> tags with themselves as the link. Is that correct, and if so, how do I do it? Also, how would I make it so that the links open in a new tab, instead of replacing my page?

EDIT This took me quite a bit of trial and error, but this PHP function should work in all realistic scenarios:

function formatTextLinks($text) {
    $words = preg_split("/[\s,]+/", $text);
    $offset = 0;

    foreach($words as $value) {
        preg_match("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", $value, $matches);

        $s = $matches[0];
        if(!is_string($s)) continue;
        $pos = strpos($text, $s, $offset);
        if($pos !== false) {
            $helper = "";
            if(strpos($s, "http://") === false || strpos($s, "https://") === false) $helper = "http://";
            $text = substr_replace($text, "<a href='".$helper.$s."' target='_blank'>".$s."</a>", $pos, strlen($s));
            $offset = $pos + strlen("<a href='".$helper.$s."' target='_blank'>".$s."</a>");
        }
    }

    return $text;
}

Upvotes: 2

Views: 1964

Answers (1)

IgorAlves
IgorAlves

Reputation: 5550

You could use a php or javascript regular expression to test if it is a URL (link). If yes create a html link tag using jquery.

This is the regex pattern

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

This is the source http://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149

Upvotes: 2

Related Questions