2012-04-13 80 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);