6
$pattern = "/\[(.*?)\]\((.*?)\)/i";
$replace = "<a href=\"$2\" rel=\"nofollow\">$1</a>";
$text = "blah blah [LINK1](http://example.com) blah [LINK2](http://sub.example.com/) blah blah ?";
echo preg_replace($pattern, $replace, $text);

上記は機能しますが、誤って [] と () の間にスペースが挿入された場合、すべてが壊れて 2 つのリンクが 1 つに混ざってしまいます。

$text = "blah blah [LINK1] (http://example.com) blah [LINK2](http://sub.example.com/) blah blah ?";

それを壊すのは怠惰な星だと感じていますが、繰り返しリンクを一致させる方法が他にわかりません。

4

2 に答える 2

9

私があなたを正しく理解していれば、実際に必要なことは、2つの間の任意の数のスペースも一致させることだけです。次に例を示します。

/\[([^]]*)\] *\(([^)]*)\)/i

説明:

\[             # Matches the opening square bracket (escaped)
([^]]*)        # Captures any number of characters that aren't close square brackets
\]             # Match close square bracket (escaped)
 *             # Match any number of spaces
\(             # Match the opening bracket (escaped)
([^)]*)        # Captures any number of characters that aren't close brackets
\)             # Match the close bracket (escaped)

理由:

私はおそらく、私があなたを変えた理由を正当化する必要があり.*?ます[^]]*

2 番目のバージョンは、大量のバックトラッキングを行う必要がないため、より効率的です.*?。さらに、開口部[が検出されると、.*? バージョンは一致が見つかるまで検索を続けます。必要なタグではない場合に失敗するのではありません。たとえば、.*?に対して使用して式を一致させる場合:

Sad face :[ blah [LINK1](http://sub.example.com/) blah

それは一致します

[ blah [LINK1]

http://sub.example.com/

この[^]]*アプローチを使用することは、入力が正しく一致することを意味します。

于 2012-05-13T11:31:30.343 に答える
0

これを試して:

$pattern = "/\[(.*?)\]\s?\((.*?)\)/i";

\s?\[(.*?)\]と の間に追加\((.*?)\)

于 2012-05-13T11:31:44.950 に答える