首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于bbcode链接+非bbcode URL的REGEX

用于bbcode链接+非bbcode URL的REGEX
EN

Stack Overflow用户
提问于 2013-06-17 23:51:22
回答 1查看 850关注 0票数 0

对于如何以最好的方式做到这一点,Tehre似乎没有一个明确的答案。

我有一些bbcode,可能有bbcode格式的链接:

url=http://thisisalink.comlink/url

以及可能的复制/粘贴urls:

http://thisisalink.com

我想用一个可点击的链接替换这两个实例。我目前正在运行以下代码: regexs:

代码语言:javascript
复制
"/\[link=http:\/\/(.*?)\](.*?)\[\/link\]/is"
"/\[link=https:\/\/(.*?)\](.*?)\[\/link\]/is"
"/\[link=(.*?)\](.*?)\[\/link\]/is"

$URLRegex = '/(?:(?<!(\[\/link\]|\[\/link=))(\s|^))'; // No [url]-tag in front and is start of string, or has whitespace in front
$URLRegex.= '(';                                    // Start capturing URL
$URLRegex.= '(https?|ftps?|ircs?):\/\/';            // Protocol
$URLRegex.= '\S+';                                  // Any non-space character
$URLRegex.= ')';                                    // Stop capturing URL
$URLRegex.= '(?:(?<![[:punct:]])(\s|\.?$))/i';      // Doesn't end with punctuation and is end of string, or has whitespace after

只是看起来我不能让两个人都工作。在这种情况下,最后一个正则表达式似乎取消了第一个正则表达式的链接。

当然,这已经在某个地方记录下来了,这是让bbcode链接和粘贴的URL链接在一起而不相互冲突的最佳方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-18 19:48:59

我最终选择了这个。然后我传递给它do回调,它允许我在php中做一些特殊的代码来做一些链接检查:

代码语言:javascript
复制
# MATCH '?://www.link.com' and make it a bbcode link
$URLRegex = '/(?:(?<!(\[\/link\]|\[\/link=))(\s|^))'; // No [url]-tag in front and is start of string, or has whitespace in front
$URLRegex.= '(';                                    // Start capturing URL
$URLRegex.= '(https?|ftps?|ircs?|http?|ftp?|irc?):\/\/';            // Protocol
$URLRegex.= '\S+';                                  // Any non-space character
$URLRegex.= ')';                                    // Stop capturing URL
$URLRegex.= '(?:(?<![[:punct:]])(\s|\.?$))/i';
$output = preg_replace($URLRegex, "$2[link=$3]$3[/link]$5", $output);

# MATCH 'www.link.com' and make it a bbcode link
$URLRegex2 = '/(?:(?<!(\[\/link\]|\[\/link=))(\s|^))'; // No [url]-tag in front and is start of string, or has whitespace in front
$URLRegex2.= '(';                                    // Start capturing URL
$URLRegex2.= 'www.';            // Protocol
$URLRegex2.= '\S+';                                  // Any non-space character
$URLRegex2.= ')';                                    // Stop capturing URL
$URLRegex2.= '(?:(?<![[:punct:]])(\s|\.?$))/i';
$output = preg_replace($URLRegex2, "$2[link=http://$3]$3[/link]$5", $output);


# link up a [link=....]some words[/link]
$output = preg_replace_callback(
    "/\[link=(.*?):\/\/(.*?)\](.*?)\[\/link\]/is", 
    Array($this,'bbcode_format_link1'),
    $output);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17151716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档