正则表达式选择url,除非=直接在它面前

时间:2016-02-06 16:11:53

标签: php regex

我正在尝试使用正则表达式来查找和替换论坛系统中的所有网址。这有效但它也可以选择bbcode中的任何内容。这不应该发生。

我的代码如下:

<?php
function make_links_clickable($text){
    return preg_replace('!(([^=](f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);
}
//$text = "https://www.mcgamerzone.com<br>http://www.mcgamerzone.com/help/support<br>Just text<br>http://www.google.com/<br><b>More text</b>";
$text = "@Theareak We know this and [b][url=https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks]here[/url] [/b]is an explanation, we are trying to fix this asap! https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks aaa";
echo "<b>Unparsed text:</b><br>";
echo $text;
echo "<br><br>";
echo "<b>Parsed text:</b><br>";
echo make_links_clickable($text);
?>

bb-code中出现的所有网址都跟随一个=字符,这意味着我不希望选择以=开头的任何内容。

我基本上有这个工作,但这导致在应该选择的字符串前面选择1个额外字符。

我对正则表达式不太熟悉。我的代码的最终输出是:

My HTML

<b>Unparsed text:</b><br>
@Theareak We know this and&nbsp;&#65279;[b][url=https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks]here[/url]&nbsp;[/b]is an explanation, we are trying to fix this asap! https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks aaa<br>
<br>
<b>Parsed text:</b><br>
@Theareak We know this and&nbsp;&#65279;[b][url=https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks]here[/url]&nbsp;[/b]is an explanation, we are trying to fix this asap!<a href=" https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks"> https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks</a> aaa

2 个答案:

答案 0 :(得分:2)

您可以匹配并跳过[url=...],如下所示:

\[url=[^\]]*](*SKIP)(?!)|(((f|ht)tps?://)[-a-zA-Zа-яёЁА-Я()0-9@:%_+.\~#?&;/=]+)

请参阅regex demo

这样,您只会匹配[url=...]代码之外的网址。

IDEONE demo

function make_links_clickable($text){
    return preg_replace('~\[url=[^\]]*](*SKIP)(?!)|(((f|ht)tps?://)[-a-zA-Zа-яёЁА-Я()0-9@:%_+.\~#?&;/=]+)~iu', '<a href="$1">$1</a>', $text);
}
$text = "@Theareak We know this and [b][url=https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks]here[/url] [/b]is an explanation, we are trying to fix this asap! https://www.mcgamerzone.com/news/67/False-positive-proxy-bans-and-bot-attacks aaa";
echo "<b>Parsed text:</b><br>";
echo make_links_clickable($text);

答案 1 :(得分:2)

你可以使用负面的后视set loc_area = -R-63.2/-61.2/15.75/17.75 set loc_proj = -Jm3.25i set outfile = bath_map.ps psbasemap $loc_area $loc_proj -O -Bf1a1WSen:.'Montserrat Local': -X7.5i -Y0 -K >> $outfile grdimage $loc_area $loc_proj -O -Clant.cpt lant_topo.nc -K >> $outfile grdcontour lant_topo.nc -Ccont.cpt -A- -Q100 -W $loc_area $loc_proj -O -K >> $outfile 而不是你的否定类。它声称要匹配的东西之前没有东西。

Example