推 LPH66:因為你的 match 字串裡有包含 "http" 的前一個字, 01/06 21:43
→ LPH66:但取代字串裡沒有, 所以就被吃掉了 01/06 21:44
→ LPH66:兩種解法, 一種是 lookbehind assertion, 01/06 21:44
→ LPH66:另一種是把那個字也 () 起來搬進取代字串裡 01/06 21:44
推 s25g5d4:PHP 的 REGEX 應該支援性比 JavaScript 好 樓上的方法1應 01/06 21:47
→ s25g5d4:該可以用 JS 只能用方法2... 01/06 21:47
→ s25g5d4:(?<=[^\]])(https?.... 01/06 21:48
原來那麼簡單~真謝謝前輩的指引。
$text = <<<EOT
中文http://www.google.com
12345http://www.google.com
http://www.google.com
]http://www.google.com
EOT;
echo preg_replace("!([^\]])(https?:/{2}[\w\.]{2,}[/\w\-\.\?\&\=\#\~\%]*)!i",
"$1<a href=\"$2\" title=\"$2\" target=\"_blank\">$2</a>",$text);
執行結果:
中文<a href="http://www.google.com" title="http://www.google.com"
target="_blank">http://www.google.com</a>
12345<a href="http://www.google.com" title="http://www.google.com"
target="_blank">http://www.google.com</a>
<a href="http://www.google.com" title="http://www.google.com"
target="_blank">http://www.google.com</a>
]http://www.google.com
※ 編輯: KC73 來自: 123.192.161.248 (01/06 23:29)