PHP Regular Expression Text URL to HTML Link
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&l开发者_如何学Pythont;/b>','<b>\\1</b>','<i>\\1</i>','<u>\\1</u>','<br />');
$msg = preg_replace($patterns, $replacements, $msg);
return stripslashes(utf8_encode($msg));
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 ) );
精彩评论