treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Php/Javascript to Find All Email Addresses, and Make Links From Them.

  • Basically I have this in the html:
    <td>example@example.com</td>

    And I want to have php make that into this:
    <td><a href="example@example.com">example@example.com</a></td>

    If necessary, I could use javascript, but I'd like to keep this to the server-side.
  • Something along the lines of this? :
    <?php
    $content ='<table><tr><td>example@example.com</td><td>example@example.co.uk</td></tr></table>';

    $addr_pattern = '/([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})(\((.+?)\))?/i';
    preg_match_all($addr_pattern, $content, $addresses);
    $the_addrs = $addresses[0];
    for ($a = 0; $a < count($the_addrs); $a++) {
    $repaddr[$a] = preg_replace($addr_pattern, '<a href="mailto:$1@$2.$3">$1@$2.$3</a>', $the_addrs[$a]);
    }
    $cc = str_replace($the_addrs, $repaddr, $content);

    echo $cc;
    ?>


    based on : http://stackoverflow.com/questions/5068676/regex-to-detect-plain-email-and-mailto-link-emails
  • There is a wordpress plugin that does this really well. I would suggest taking a look at the source code and seeing what you can get from it. http://www.semiologic.com/software/autolink-uri/