1

Is there anyway to convert plain text URLs to HTML hyperlinks in PHP? I need to convert URLs of following type:

http://example.com
http://example.org
http://example.gov/
http://example.com?q=sometext&opt=thisandthat
http://example.com#path
http://example.com?q=querypath#path
http://example.com/somepath/index.html

https://example.com/
https://example.org/
https://example.gov/
https://example.com?q=sometext&opt=thisandthat
https://example.com#path
https://example.com?q=querypath#path
https://example.com/somepath/index.html

http://www.example.com/
http://www.example.org/
http://www.example.gov/
http://www.example.com?q=sometext&opt=thisandthat
http://www.example.com#path
http://www.example.com?q=querypath#path
http://www.example.com/somepath/index.html

https://www.example.com/
https://www.example.org/
https://www.example.gov/
https://www.example.com?q=sometext&opt=thisandthat
https://www.example.com#path
https://www.example.com?q=querypath#path
https://www.example.com/somepath/index.html

www.example.com/
www.example.org/
www.example.gov/
www.example.com?q=sometext&opt=thisandthat
www.example.com/#path
www.example.com?q=querypath#path
www.example.com/somepath/index.html

example.com/
example.org/
example.gov/
example.com?q=sometext&opt=thisandthat
example.com/#path
example.com?q=querypath#path
example.com/somepath/index.html
Amit
  • 712
  • 2
  • 13
  • 26
  • Is that coming from external file you want to parse using php? – Sarfraz Aug 10 '10 at 18:50
  • What do you want the links to read? Are these links in a file or an array or something else? – Peter Ajtai Aug 10 '10 at 18:50
  • I guess you’re looking for a way to find such URLs in a text, convert them to full URLs and replace them by HTML links, right? – Gumbo Aug 10 '10 at 19:16
  • Links would come from user input. I am providing a textarea to input comments on my site. Any URL in the comment needs to be converted into a link. – Amit Aug 11 '10 at 04:46

7 Answers7

3

How about running them through a regular expression like the following used to re-activate Twitter links -

http://www.burnmind.com/howto/how-to-convert-twitter-mentions-and-urls-to-active-links-using-regular-expressions-in-php

bulkhead
  • 108
  • 1
  • 11
2

If you just need to convert a single URL, it's quite easy:

function makeLink($url)
{
    return '<a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a>';
}

For URLs appearing in a larger text block, e.g. user comments, see this question:

Community
  • 1
  • 1
Søren Løvborg
  • 8,354
  • 2
  • 47
  • 40
2

Try this function. this will make link if text start with http or www. example.com will not work.

function linkable($text = ''){
    $text = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text));
    $data = '';
    foreach( explode(' ', $text) as $str){
        if (preg_match('#^http?#i', trim($str)) || preg_match('#^www.?#i', trim($str))) {
            $data .= '<a href="'.$str.'">'.$str.'</a> ';
        } else {`enter code here`
            $data .= $str .' ';
        }
    }
    return trim($data);
}
Shanto
  • 21
  • 1
0

Er, wrap them in an anchor tag?

function linkify($url) {
  return '<a href="' . $url . '">' . $url . '</a>';
}
Frank Shearar
  • 17,012
  • 8
  • 67
  • 94
  • This code doesn't work, since it doesn't perform HTML escaping of the URL. Most importantly, URLs containing ampersands will yield invalid HTML. – Søren Løvborg May 27 '11 at 17:04
  • It doesn't do a whole bunch of things. I intended nothing more than the smallest example that demonstrated the concept. – Frank Shearar May 27 '11 at 20:05
0

Here is how I did it (with test cases included):

/**
 * @see Inspired by https://css-tricks.com/snippets/php/find-urls-in-text-make-links/ and Example 1 of http://php.net/manual/en/function.preg-replace-callback.php
 * 
 * @param string $text
 * @return string
 */
public static function getTextWithLinksEnabled($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, $text);
}

Tests:

public function testGetTextWithLinksEnabled() {
    $this->assertEquals('a@b.com', StrT::getTextWithLinksEnabled('a@b.com'));//no links
    $this->assertEquals('just plain text', StrT::getTextWithLinksEnabled('just plain text'));//no links
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here'));//one link
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here and another: <a href='https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'>https://css-tricks.com/snippets/php/find-urls-in-text-make-links/</a>", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here and another: https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'));//2 links
}
Ryan
  • 22,332
  • 31
  • 176
  • 357
0

This is what I use to do the same thing on a small forum I made. Generally I run the whole comment through it like echo makeLinks($forumpost['comment']);

function makeLinks($str) {    
    return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%,]+)/i', '<a href="$1://$2" target="_blank">$1://$2</a>', $str);
}
cOle2
  • 4,725
  • 1
  • 24
  • 26
-1

In case the end user doesn't include 'http://' or 'https://' (in my case copying a link into a form). Based on Ryan's code above me:

function makeLink($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        // $fullMatch = startsWith($fullMatch, 'http') ? $fullMatch : 'http://'.$fullMatch;
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, substr( $text, 0, strlen( 'http' ) ) === 'http' ? $text : 'http://'.$text);
}
dev-jeff
  • 173
  • 9