-1

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

$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 replace 它将不起作用。

4

2 回答 2

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);
?>

奇迹般有效。

于 2013-09-30T02:23:44.653 回答
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{}{{{}"
于 2013-09-30T02:25:29.097 回答