看板 RegExp 關於我們 聯絡資訊
各位好: 使用的是 PHP 5.3.27,要抓出文中的以 http 開頭的連結,但是如果 http 前面是 ], 就不抓: $text = <<<EOT 12345http://www.google.com http://www.google.com ]http://www.google.com EOT; echo preg_replace("![^\]](https?:/{2}[\w\.]{2,}[/\w\-\.\?\&\=\#\~\%]*)!i", "<a href=\"$1\" title=\"$1\" target=\"_blank\">$1</a>", $text); 結果: 1234<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 第一行的「12345http://www.google.com」的「5」被吃掉了,不知為何? 謝謝~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.192.161.248
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)