Php – parse text and convert urls into hyperlinks

By | May 10, 2020

The following function will parse a given text and convert all the urls into links. It does this using regular expressions. It converts email addresses to mailto links as well.

Code

function parse_links($str)
{
    $str = str_replace('www.', 'http://www.', $str);
    $str = preg_replace('|http://([a-zA-Z0-9-./]+)|', '<a href="http://$1">$1</a>', $str);
    $str = preg_replace('/(([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@([a-z0-9-]+.)+[a-z]{2,6})/', '<a href="mailto:$1">$1</a>', $str);
    return $str;
}
About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

2 Comments

Php – parse text and convert urls into hyperlinks

Leave a Reply

Your email address will not be published. Required fields are marked *