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://.

  • possible duplicate of [Replace URLs in text with HTML links](http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links) and check: http://stackoverflow.com/questions/9704111/only-replace-own-website-url-in-text-with-html-links?rq=1 – Luceos Apr 30 '14 at 16:29
  • @Luceos it is not a duplicate, I want the system to detect all of the URLs, not one specific. –  Apr 30 '14 at 16:34
  • @VladGincher Luceos's answer is exactly what you try to do nop ? – kero_zen Apr 30 '14 at 16:41
  • 1
    @VladGincher just check the first linked url: http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links ; using preg replace and/or preg replace callback is what you need. – Luceos Apr 30 '14 at 16:53

1 Answers1

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
'));
?>
Rolice
  • 3,063
  • 2
  • 24
  • 32