Advertisement
sscovil

Convert URLs and Email Addresses into HTML Links

Nov 11th, 2011
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.24 KB | None | 0 0
  1. <?php
  2.  
  3. $link = 'Link #1 = http://mynewsitepreview.com/ and Link #2 = www.mynewsitepreview.com';
  4. echo findlinks($link);
  5.  
  6. function findlinks($text) {
  7.  
  8.     $email_pattern = "/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/i";
  9.     $url_pattern = "/((http|https|ftp|sftp):\/\/)[a-z0-9\-\._]+\/?[a-z0-9_\.\-\?\+\/~=&#;,]*[a-z0-9\/]{1}/si";
  10.     $www_pattern = "/[^>](www)[a-z0-9\-\._]+\/?[a-z0-9_\.\-\?\+\/~=&#;,]*[a-z0-9\/]{1}/si";
  11.  
  12.     // First, check if the string contains an email address...
  13.     if( preg_match( $email_pattern, $text, $email ) ) {
  14.         $replacement = '<a href="mailto:' . $email[0]. '">' . $email[0] . '</a> ';
  15.         $text = preg_replace($email_pattern, $replacement, $text);
  16.     }
  17.     // Next, check if the string contains a URL beginning with http://, https://, ftp://, or sftp://
  18.     if( preg_match( $url_pattern, $text, $url ) ) {
  19.         $replacement = '<a href="' . $url[0] . '">' . $url[0] . '</a>';
  20.         $text = preg_replace($url_pattern, $replacement, $text);
  21.     }
  22.     // Last, check for a plain old www address (without a closing HTML tag before them)
  23.     if( preg_match( $www_pattern, $text, $www ) ) {
  24.         $replacement = ' <a href="http://' . ltrim( $www[0] ). '">' . ltrim( $www[0] ) . '</a> ';
  25.         $text = preg_replace($www_pattern, $replacement, $text);
  26.     }
  27.  
  28.     return $text;
  29.  
  30. }
  31. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement