2013-09-30 70 views
-1

由于ereg替换已折旧,我想知道如何使用preg来代替。这是我的代码,我需要替换{}标签。PHP如何使用preg替换而不是ereg替换?

$template = ereg_replace('{USERNAME}', $info['username'], $template); 
    $template = ereg_replace('{EMAIL}', $info['email'], $template); 
    $template = ereg_replace('{KEY}', $info['key'], $template); 
    $template = ereg_replace('{SITEPATH}','http://somelinkhere.com', $template); 

这将无法正常工作,如果我只是将它切换到preg替换。

回答

2

使用str_replace(),为什么不呢?

这样,哇:

<?php 
$template = str_replace('{USERNAME}', $info['username'], $template); 
$template = str_replace('{EMAIL}', $info['email'], $template); 
$template = str_replace('{KEY}', $info['key'], $template); 
$template = str_replace('{SITEPATH}','http://somelinkhere.com', $template); 
?> 

就像一个魅力。

+0

感谢的人的作品完美 – user2802518

+0

@ user2802518因此将其标记为一个解决方案:)谢谢! “ –

0

我不知道如何ereg_replace工作,但preg_replace工作正则表达式。

如果您想更换“{”和“}”

正确的方法是:

$template = preg_replace("/({|})/", "", $template); 
// if $template == "asd{asdasd}asda{ds}{{" 
// the output will be "asdasdasdasdads" 

现在,如果你想更换“{”和“}”只有当具体是在他们里面的东西,你应该执行:

$user = "whatever"; 
$template = preg_replace("/{($user)}/", "$0", $template); 
// if $template == "asd{whatever}asda{ds}" 
// the output will be "asdwhateverasda{ds}" 

如果你想要的东西,可能是从“A”到“Z”

只有字母的任何字符串替换“{”和“}”

你应该使用:

$template = preg_replace("/{([a-Z]*)}/", "$0", $template); 
// if $template == "asd{whatever}asda{ds}{}{{{}" 
// the output will be "asdwhateverasdads{}{{{}" 
+0

”使用正则表达式和正则表达式。“ - - 什么? – zerkms

+0

我试图解释preg_replace使用正则表达式模块,所以你必须使用正则表达式来进行搜索。 –

+0

什么是“正则表达式模块”? – zerkms