2

How can I detect URL in text area that doesn't include http://? Here is an a example for a input:

Hi bro! Look at my new website: www.example.com. I leard to build websites from http://another.example.net and from example.net.

Is there a way to convert it to this code?:

Hi bro! Look at my new website: <a href="http://www.example.com">www.example.com</a>.
I leard to build websites from <a href="http://another.example.com">http://another.example.net</a>
and from <a href="http://example.net">example.net</a>.

As you can see, the code detects if there are a URL even if it doesn't starts with http:// or www, and adds to the a tag the http://.

4
  • possible duplicate of Replace URLs in text with HTML links and check: stackoverflow.com/questions/9704111/… Commented Apr 30, 2014 at 16:29
  • @Luceos it is not a duplicate, I want the system to detect all of the URLs, not one specific. Commented Apr 30, 2014 at 16:34
  • @VladGincher Luceos's answer is exactly what you try to do nop ? Commented Apr 30, 2014 at 16:41
  • 1
    @VladGincher just check the first linked url: stackoverflow.com/questions/1188129/… ; using preg replace and/or preg replace callback is what you need. Commented Apr 30, 2014 at 16:53

1 Answer 1

3

See this basic example. It allows you to match in multi-line texts and it is not too restrictive. You could have links to internal network, where the machine hostname is used like: http://myspecialserver - this is valid link, no matter it might be accessible only by certain network(s).

The anwser uses the regular expressions. You can read more about them here: http://www.tutorialspoint.com/php/php_regular_expression.htm

We match with them the protocol and any text after which is consistent for URL, it does not contain space charaters, tabs, carriage returns and line feeds.

<?php
function linkify($text) {
    return preg_replace('#\b(http|ftp)(s)?\://([^ \s\t\r\n]+?)([\s\t\r\n])+#smui', '<a href="$1$2://$3">$1$2://$3</a>$4', $text);
}

echo nl2br(linkify('
    Hello, visit https://www.domain.com
    We are not partners of http://microsoft.com/ :)
    Download source from: ftp://new.sourceforge.com
'));
?>
Sign up to request clarification or add additional context in comments.

2 Comments

But it won't work if the URL doesn't include http://
Yes, it will not be a valid URL (not an URL) if it is not starting with the protocol...