This seems simple enough, but I've not found the answer.

Users are posting URLs and email addresses through a textarea in a form which saves the posts in MySQL. I'd like a snippet of code which recognises the URLs, email addresses and inserts them between HTML link tags, as follows:

Example 1

$message = "Visit http://here.com, it's great!"

-> PHP code ->

$message = "Visit <a href="http://here.com>http://here.com</a>, it's great!"

Example 2

$message = "If you find my cat, please email me at found@lostcat.com."

-> PHP code ->

$message = "If you find my cat, please email me at <a href="mailto:found@lostcat.com">found@lostcat.com</a>."

    sounds like a job for regular expressions!

    got this from php.net by marten_berglund at hotmail dot com, 18-Apr-2007 08:20 on the preg_replace page:

    <?php
    function linkify($text) {
        $strip_lchrs = "[^\s\(\)\[\]\{\}\.\,\;\:\?\!]";      //Not these chars in beginning
        $strip_rchrs = "[^\s\(\)\[\]\{\}\.\,\;\:\?\!\d]";    //Not these chars in end
    
    $prot_pat = $strip_lchrs . "[\S]*\:\/\/[\S]*\.[\S]*" . $strip_rchrs;  //abc://de.fg
    $email_pat = $strip_lchrs . "[\S]*@[\S]*\.[\S]*" . $strip_rchrs;      //abc@de.fg
    $general_pat = $strip_lchrs . "[\S]*\.[\S]*" . $strip_rchrs;          //abc.de
    
    $preg_pattern = "/(" . $prot_pat . "|" . $email_pat . "|" . $general_pat . ")/ei";
    $preg_replace = "check_preg('$1')";
    return preg_replace($preg_pattern, $preg_replace, $text);
    }
    
    function check_preg($subpat) {
        //These abbr. should not be linked
        $exc_string = "/e\.g|i\.e|et\.c/i";
        //If it says abc://de.fg
        if (preg_match("/[\S]*\:\/\/[\S]*\.[\S]*/i", $subpat) == 1) {
            return "<a href='" . $subpat . "' target='_top'>" . $subpat . "</a>";
        }
        //If it says abc@de.fg
        else if (preg_match("/[\S]*@[\S]*\.[\S]*/i", $subpat) == 1) {
            return "<a href='mailto:" . $subpat . "'>" . $subpat . "</a>";
        }
        //If it says "e.g." don't link
        else if (preg_match($exc_string, $subpat) == 1) {
            return $subpat;
        }
        //If it says abc.de
        else
            return "<a href='http://" . $subpat . "' target='_top'>" . $subpat . "</a>";
    }
    ?>

    hope this helps.

      Thanks very much for that. Looks like just what I'm after. Having some initial problems installing it into my script, but I should hopefully work through it.

        Write a Reply...