Skip to main content

Replace URL's and email addresses with HTML formated anchor tags.

<?php 

if (!function_exists('replace_url_with_link')) {
  /**
   * Replaces URL's with HTML links (anchor tag).
   *
   * @access public
   * @param string $input The input.
   * @return string
   * @example http://abc.com => <a href="http://abc.com">http://abc.com</a>
   */
  function replace_url_with_link($input) {
    return preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/i', '<a href="\0">\0</a>', $input);
  }
}

if (!function_exists('replace_email_with_link')) {
  /**
   * Replaces email addresses with HTML links (anchor tag).
   * 
   * @access public
   * @param string $input The input.
   * @return string
   * @example jon@doe.com => <a href="mailto:jon@doe.com">jon@doe.com</a>
   */
  function replace_email_with_link($input) {
    return preg_replace('/\b(?:mailto:)?([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6})\b/i', '<a href="mailto:\1">\0</a>', $input);
  }
}

?>