PHP preg_replace - www 或 http:// [英] PHP preg_replace - www or http://
问题描述
真的坚持看似简单的事情.我有一个聊天框/留言框,其中可能输入了任意 URL.我想找到每个单独的 URL(用空格分隔)并将其包装在标签中.
Really stuck on what seems to be something simple. I have a chatbox/shoutbox where there may be arbitrary URLs entered. I want to find each individual URL (separated by spaces) and wrap it in tags.
示例:Harry 你是一个 http://google.com 向导!
=Harry 你是一个 $lhttp://google.com$l 向导!
示例:Harry 你是一个 http://www.google.com 向导!
= Harry 你是一个 $lhttp://www.google.com$l 向导!
示例:Harry,您是 www.google.com 的向导!
= Harry,您是 $lwww.google.com$l 的向导!
对不起,如果这是一个愚蠢的问题;我只是想让一些东西工作,我不是 php 专家:(
Sorry if this is a daft question; I'm just trying to make something work and I'm no php expert :(
推荐答案
有一篇关于 URL 正则表达式.在 PHP 中,这看起来像:
There is an interesting article about a URL regular expression. In PHP this would look like:
$pattern = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»""‘’]))/";
$inp = "Harry you're a http://google.com wizard!";
$text = preg_replace($pattern, "[supertag]$1[/supertag]", $inp);
当然用适当的值替换[supertag]
和[/supertag]
.
And of course replace [supertag]
and [/supertag]
with the appropriate values.
这篇关于PHP preg_replace - www 或 http://的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!