2010-10-20 85 views
6
preg_replace("/{{(.*?)}}/e","$$1",$rcontent); 

請解釋聲明,我...我無法理解這PHP的preg_replace

+0

匹配"def"爲什麼投票關閉這個?很明顯,問題在於詢問正則表達式的含義。 – JAL 2010-10-20 05:00:06

+0

@亞歷克斯JL:我沒有投票結束,但它一定是標題。我不知道元標籤與這個問題有什麼關係。 – BoltClock 2010-10-20 05:24:04

+0

@BoltClock它很神祕。 – JAL 2010-10-20 06:30:43

回答

4

考慮這樣一個例子使用:

$rcontent = "abc {{foo}} def"; 
$foo = 'bar'; 
$rcontent = preg_replace("/{{(.*?)}}/e","$$1",$rcontent); 
echo $rcontent; // prints abc bar def 

我假設你正在分配的preg_match值回到$rcontent,否則它沒有任何意義。

現在正在使用的正則表達式是{{(.*?)}}看起來對{{}}之間的任何(非greedyly),還記得因爲括號匹配的字符串。
在我的情況下,.*?匹配foo

接下來的替換部分是$$1。現在$1foo,所以$$1將是$foo這就是bar。因此{{foo}}將被替換爲$foo的值bar

如果$$1僅僅是一個類型,你想用$1那麼正則表達式替換{{foo}}foo

+0

$ file = file(「templates/index.html」); $ rcontent = join(「」,$ file); $ rcontent = preg_replace(「/{{(.*?)}}/ e」,「$$ 1」,$ rcontent); print $ rcontent; 這是我的code.its工作完美..但模板/ index.html文件沒有任何palenthesis它.. – sowmiya 2010-10-20 06:13:28

+0

@sowmiya:對不起,我沒有得到你的問題。 – codaddict 2010-10-20 07:31:36

+0

正在將「templates/index.html」的內容複製到一個php文件中....要使用此正則表達式複製內容,我在「templates/index.html」文件中沒有任何大括號。但它完美的作品..如何這個模板引擎工作我不知道... – sowmiya 2010-10-20 08:50:46