1

I'm working on a project where I need to replace text urls anywhere from domain.com to www.domain.com to http(s)://www.domain.com and e-mail addresses to the proper html <a> tag. I was using a great solution in the past, but it used the now depreciated eregi_replace function. On top of that, the regular expression used for such function does not work with preg_replace.

So basically, the user inputs a message in which may/may not contain a link/e-mail address and I need a regular expression that works with preg_replace to replace that link/email with a HTML link like <a href="link">link</a>.

Please note that I have multiple other preg_replaces too. Below is my current code for the other replacements being made.

$patterns = array('~\[@([^\]]*)\]~','~\[([^\]]*)\]~','~{([^}]*)}~','~_([^_]*)_~','/\s{2}/');
$replacements = array('<b class="reply">@\\1</b>','<b>\\1</b>','<i>\\1</i>','<u>\\1</u>','<br />');
$msg = preg_replace($patterns, $replacements, $msg);
return stripslashes(utf8_encode($msg));

1 Answer 1

6

I have created a very basic set of Regular Expressions for this. Don't expect them to be 100% reliable, and you may need to tweak them as you go.

$pattern = array(
  '/((?:[\w\d]+\:\/\/)?(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d]+\&?)?(?:\#[\w\-\d]*)?)/' , # URL
  '/([\w\-\d]+\@[\w\-\d]+\.[\w\-\d]+)/' , # Email
  '/\[@([^\]]*)\]/' , # Reply
  '/\[([^\]]*)\]/' , # Bold
  '/\{([^}]*)\}/' , # Italics 
  '/_([^_]*)_/' , # Underline
  '/\s{2}/' , # Linebreak
);
$replace = array(
  '<a href="$1">$1</a>' ,
  '<a href="mailto:$1">$1</a>' ,
  '<b class="reply">@$1</b>' ,
  '<b>$1</b>' ,
  '<i>$1</i>' ,
  '<u>$1</u>' ,
  '<br />'
);
$msg = preg_replace( $pattern , $replace , $msg );
return stripslashes( utf8_encode( $msg ) );
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent man! You know what you are doing! I appreciate your help with this one.
quick note - add a semicolon after the closing ) for $replace.
@Lucanos this is great, but the url one, doesn't support parenthesis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.