[問題] PHP preg_replace 的問題

看板RegExp (正規表示式 Regular Expression)作者 (肯先生)時間10年前 (2014/01/06 21:40), 編輯推噓2(205)
留言7則, 2人參與, 最新討論串1/1
各位好: 使用的是 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

01/06 21:43, , 1F
因為你的 match 字串裡有包含 "http" 的前一個字,
01/06 21:43, 1F

01/06 21:44, , 2F
但取代字串裡沒有, 所以就被吃掉了
01/06 21:44, 2F

01/06 21:44, , 3F
兩種解法, 一種是 lookbehind assertion,
01/06 21:44, 3F

01/06 21:44, , 4F
另一種是把那個字也 () 起來搬進取代字串裡
01/06 21:44, 4F

01/06 21:47, , 5F
PHP 的 REGEX 應該支援性比 JavaScript 好 樓上的方法1應
01/06 21:47, 5F

01/06 21:47, , 6F
該可以用 JS 只能用方法2...
01/06 21:47, 6F

01/06 21:48, , 7F
(?<=[^\]])(https?....
01/06 21:48, 7F
原來那麼簡單~真謝謝前輩的指引。 $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)
文章代碼(AID): #1Ioh965u (RegExp)
文章代碼(AID): #1Ioh965u (RegExp)