在 [code] 和 [php] 标签中查找 URL [英] Find URL Inside a [code] and [php] tag

查看:22
本文介绍了在 [code] 和 [php] 标签中查找 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串是这样的:

$string = '
Link_1: [code]This is a textual line.
www.google.com
This is a textual line.[/code]

Link_2: [php]This is a textual line.
www.google.com
This is a textual line.[/php]
';

我想使用 REGEX 以便我可以替换此字符串中的 URL 并且应该像这样返回:

I want to use a REGEX so that I could replace the URL inside this string and should return like this:

Link_1: [code]This is a textual line.
LINK HIDDEN
This is a textual line.[/code]

Link_2: [php]This is a textual line.
LINK HIDDEN
This is a textual line.[/php]

我是一个 REGEX 菜鸟,所以请帮我找到一个正确的 REGEX 以获得上述结果,谢谢

I am a REGEX noob so please help me to find a correct REGEX to get the result mentioned above, thank you

推荐答案

使用正向前瞻来检查将要匹配的链接后是否没有结束 php 或代码标记.

Use a positive lookahead to check for the links which are going to be matched wouldn't be followed by a closing php or code tag.

$content = <<<EOS
Link_1: [code]This is a textual line.
www.google.com
This is a textual line.[/code]

Link_2: [php]This is a textual line.
www.google.com
This is a textual line.[/php]
EOS;
$needle = '~(?:https?://)?(?:www\.)(?:[^.\s]+)(?:\.[^.\n\s]+)*\.\w{2,4}(?=(?:(?!\[/?(?:code|php)])[\S\s])*\[/(?:code|php)])~m';
echo preg_replace($needle,'LINK HIDDEN',$content);

输出:

Link_1: [code]This is a textual line.
LINK HIDDEN
This is a textual line.[/code]

Link_2: [php]This is a textual line.
LINK HIDDEN
This is a textual line.[/php]

这篇关于在 [code] 和 [php] 标签中查找 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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