叹息,正则表达式又麻烦了。
我有以下内容$text
:
[img]http://www.site.com/logo.jpg[/img]
and
[url]http://www.site.com[/url]
我有正则表达式:
$text = preg_replace("/(?<!(\[img\]|\[url\]))([http|ftp]+:\/\/)?\S+[^\s.,>)\];'\"!?]\.+[com|ru|net|ua|biz|org]+\/?[^<>\n\r ]+[A-Za-z0-9](?!(\[\/img\]|\[\/url\]))/","there was link",$text);
关键是仅在 url 前面没有[img]
or[url]
且后面没有[/img]
or的情况下才替换它[/url]
。在上一个示例的输出中,我得到:
there was link
and
there was link
URL 和lookbehind 和lookbehind 正则表达式都可以单独工作。
$text = "[img]bash.org/logo.jpg[/img]";
$text = preg_replace("/(?<!(\[img\]|\[url\]))bash.org(?!(\[\/img\]|\[\/url\]))/","there was link",$text);
echo $text leaves everything as is and gives me [img]bash.org/logo.jpg[/img]
我想问题在于环视和 URL 正则表达式的组合。我的错在哪里?
我想要
将http://www.google.com替换为“有链接”,但保持原样“[url] http://www.google.com[/url] ”
我越来越
http://www.google.com替换为“有链接”,[url] http://www.google.com[/url]替换为“有链接”
这是要测试的 PHP 代码
<?php
$text = "[url]http://www.google.com[/url] <br><br> http://www.google.com";
// should NOT be changed //should be changed
$text = preg_replace("/(?<!\[url\])([http|ftp]+:\/\/)?\S+[^\s.,>)\];'\"!?]\.+[com|ru|net|ua|biz|org]+\/?[^<>\n\r ]+[A-Za-z0-9](?!\[\/url\])/","there was link",$text);
echo $text;
echo '<hr width="100%">';
$text = ":) :-) 0:) 0:-) :)) :-))";
$text = preg_replace("/(?<!0):-?\)(?!\))/","smiley",$text);
echo $text; // lookarounds work
echo '<hr width="100%">';
$text = "http://stackoverflow.com/questions/2482921/regexp-exclusion";
$text = preg_replace("/([http|ftp]+:\/\/)?\S+[^\s.,>)\];'\"!?]\.+[com|ru|net|ua|biz|org]+\/?[^<>\n\r ]+[A-Za-z0-9]/","it's a link to stackoverflow",$text);
echo $text; // URL pattern works fine
?>