PHP 正则表达式文本 URL 到 HTML 链接 [英] PHP Regular Expression Text URL to HTML Link

查看:26
本文介绍了PHP 正则表达式文本 URL 到 HTML 链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,我需要替换从 domain.comwww.domain.comhttp(s) 的任何地方的文本网址://www.domain.com 和电子邮件地址到正确的 html 标签.过去我使用了一个很好的解决方案,但它使用了现已贬值的 eregi_replace 函数.最重要的是,用于此类函数的正则表达式不适用于 preg_replace.

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.

所以基本上,用户输入一条消息,其中可能/可能不包含链接/电子邮件地址,我需要一个与 preg_replace 一起使用的正则表达式来替换该链接/电子邮件HTML 链接,如 link.

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>.

请注意,我也有多个其他 preg_replaces.下面是我当前用于其他替换的代码.

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));

推荐答案

我为此创建了一组非常基本的正则表达式.不要期望它们 100% 可靠,您可能需要随时调整它们.

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 ) );

这篇关于PHP 正则表达式文本 URL 到 HTML 链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆