在[code]和[php]标签内查找URL

时间:2014-11-01 11:25:03

标签: php regex

我的字符串是这样的:

$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并应该像这样返回:

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来获得上面提到的结果,谢谢

1 个答案:

答案 0 :(得分:1)

使用正向前瞻来检查将要匹配的链接,然后是关闭的php或代码标记。

$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]