はぁ、また正規表現トラブル。
私は以下を持っています$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);
[img]
ポイントは、前にor[url]
がなく、後に[/img]
orがない場合にのみ url を置き換えること[/url]
です。前の例の出力では、次のようになります。
there was link
and
there was link
URL と後読みおよび先読み正規表現の両方が別々に正常に動作しています。
$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を「there was link」に置き換えますが、「[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
?>