2013-06-29 138 views
1

我的網站最近爆炸了,因爲eregi_replace被淘汰。現在我需要將它們轉換爲preg_replace或其他東西。這與我的大部分功能一起工作,但我遇到了模擬bbtags的問題。修復eregi_replace函數

有人可以幫忙嗎?

$txt = eregi_replace("\\[url\\]([^\\[]*)\\[/url\\]", "<a href=\"\\1\" target=\"_blank\">\\1</a>", $txt); 
$txt = eregi_replace("\\[img\\]([^\\[]*)\\[/img\\]", "<a href=\"\\1\"><img src=\"\\1\" width=\"150px\" height=\"150px\" style=\"float: left; margin-right: 10px;\" /></a>", $txt); 
$txt = eregi_replace("\\[cimg\\]([^\\[]*)\\[/cimg\\]", "<a href=\"\\1\"><img src=\"\\1\" width=\"100px\" height=\"100px\" /></a>", $txt); 
$txt = eregi_replace("\\[code\\]([^\\[]*)\\[/code\\]", "<br><br><strong>Code:</strong><table width=\"80%\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\" bgcolor=\"#FFFFFF\" style=\"border:1px solid gray;\"><tr><td bgcolor=\"#FFFFFF\"><font color=\"#009900\" size=\"-2\">\\1</font></td></tr></table><br>", $txt); 
+0

用'*?'替換'*'(加上你對其他正則表達式所做的所有其他「機械」的東西)應該可以解決問題。 – Jon

+0

@Jon:你不需要用'*?'替換'*',因爲這個字符類不包含方括號。 –

+0

@CasimiretHippolyte:對,我沒有仔細閱讀正則表達式,只記得兩種口味之間的默認貪婪是不同的。但我不確定爲什麼直接'preg_replace'不會工作。 – Jon

回答

1

例如:

$txt = preg_replace('~\[url]([^[]*+)\[/url]~i', '<a href="$1" target="_blank">$1</a>', $txt); 

*+意味着零次或多次(possessive

注意:您不需要逃避關閉方括號。你不需要在字符類中轉義方括號。使用簡單的引號來包圍你的字符串是最好的選擇,因爲你不必在裏面跳過雙引號。

使用\[^]]而不是點的興趣是您可以避免惰性量詞.*?並獲得更高性能的模式。第二個興趣是你避免了dotall問題,因爲這個字符類匹配換行符。

+0

我是這樣做的:\t'$ txt = preg_replace(「#\ [url \](。+?)\ [/ url \]#是」,「\\1」,$ txt);' 它可以工作,好嗎? :P – Coolcrab

+0

@Coolcrab:看我的編輯。 –