Monday 11 July 2016

PHP function to parse text to hyperlinks

Following function is used to parse text and convert the urls into links, in addition it converts mail id to mailto links. This simple function basically functions on regular expressions.

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

No comments:

Post a Comment