2012-04-21 67 views
0

我正在寫一個允許引用和引用其他用戶鏈接的留言板。留言板允許某些html標籤,包括<img>。引用消息時,我想查找<img>並用縮略圖替換圖片。這裏是我當前的代碼:REGEX用於在任意數量的嵌套自定義標籤內匹配img標籤

<?php 
$pattern = "<quote msgid=\"t,(\d+),(\d+)@(\d+)\" from=\"([A-z0-9_\.-]+)\" posted=\"(\d+)\">(.+)<img src=\"https?:\/\/i\.(minus|imgur)\.com\/([A-z0-9_\.-]+)\.(jpg|gif|png|jpeg)\"(\/)?>"; 
$replace = "<div class=\"quoted-message\" msgid=\"t,$1,[email protected]$3\"><div class=\"message-top\">From: $4 | Posted: $5</div>$6<img src=\"http:\/\/$7.com\/$8s\.$9\" />"; 
$encoded = preg_replace($pattern, $replace, $encoded); 
?> 

模式本身的工作原理,但我遇到的問題是,它沒有發揮好與嵌套引用。例如,數據可以是這樣的:

<quote msgid="t,1234,[email protected]" from"user" posted="test">Some words here<quote msgid="t,5635,[email protected]" from"user2" posted="test">Some more <b>words</b> here<quote msgid="t,1243532,[email protected]" from"user" posted="test">Something else here<img src="linktoimage"/></quote>some words can go here</quote>or here</quote> 

我現在正則表達式將會與一個div標籤更換前3開引號標記,而不是僅僅配套最內層標籤。我知道它與(.+)有關,但我不知道我能做些什麼來檢查前面的數據。

任何幫助將不勝感激。

回答

1

正則表達式並不適合您的情況(very oddly explained here)。你應該真的使用解析器。

+0

真棒,感謝輸入和娛樂性的解釋。我會研究解析器。 – Drew 2012-04-21 03:36:33

0

(?!<quote.*?<quote)(<quote)

匹配最內側報價標籤。

http://regexr.com?30ng2

+0

這個解決方案的問題是圖像標籤不一定會在最內層的標籤中。 – Drew 2012-05-05 05:06:52