PHP 正则表达式文本 URL 到 HTML 链接
我正在开发一个项目,需要替换从 domain.com
到 www.domain.com
到 http(s):// 的任何文本网址www.domain.com
和电子邮件地址添加到正确的 html 标记中。我过去使用过一个很好的解决方案,但它使用了现在已弃用的
eregi_replace
函数。最重要的是,用于此类函数的正则表达式不适用于 preg_replace
。
所以基本上,用户输入一条消息,其中可能/可能不包含链接/电子邮件地址,我需要一个与 preg_replace
配合使用的正则表达式,以使用 HTML 链接替换该链接/电子邮件,例如链接
。
请注意,我还有多个其他 preg_replace。以下是我当前正在进行的其他替换的代码。
$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));
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));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我为此创建了一组非常基本的正则表达式。不要指望它们 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.