DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Make Anchors From Urls And Email Addresses

  • submit to reddit
        This little PHP function will find urls and email addresses in a block of text and turn them into hyperlinks and mailto: anchors respectively.

function makeLinks($sourceText) {
  $destText = preg_replace( "/([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+)(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})/", '<a href="mailto:\\0">\\0</a>',$sourceText);
  $destText = preg_replace_callback('/\bhttp[^\s]+/',create_function('$matches', 'return "<a href=\"$matches[0]\">" . preg_replace("#(\.|/)#", "­$1", $matches[0]) . "</a>";'),$destText);
  return $destText;