2012-04-13 74 views
0

我試圖在文本中替換多個變量。 我有例如這樣的文字:PHP preg_repalce將%var%替換爲文本

This is an example text , my variables are: 
%name% 
%frontname% 
%lastname% 
%email% 

不,我想替換每個變量是{$變量}的%%字符之間。

所以我的輸出是這樣的:

This is an example text , my variables are: 
{$name} 
{$frontname} 
{$lastname} 
{$email} 

我想使用的模式是這樣的:

$textResponder = preg_replace('#\%[^\%]+\%#', '{$$1}', $text); 

但不工作,因爲我得到這個作爲輸出:{$} {$} {$}.不有人知道什麼是正確的模式?

在此先感謝

回答

0
$var = "Hello, %test% World %another test%!"; 
echo preg_replace('#%(.*?)%#', '{\$$1}', $var); 

Test here

+0

爲什麼你escapin g'%'字符? – 2012-04-13 08:10:32

+0

非常感謝,這很有用。 – 2012-04-13 08:11:56

+0

更新了代碼沒有逃脫,結果不會改變,只是使它更清潔一點。 – 2012-04-13 08:33:12

0

嘗試

preg_replace('/%(.*?)%/', '{\$$1}', $text); 
0

@Gert範·德溫您需要逃離美元的特殊含義:

$var = "Hello, %test% World!"; 
echo preg_replace('#\%(.*?)\%#', '{\$$1}', $var);