Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP如何使用preg replace而不是ereg replace?_Php_Regex - Fatal编程技术网

PHP如何使用preg replace而不是ereg replace?

PHP如何使用preg replace而不是ereg replace?,php,regex,Php,Regex,由于ereg replace已贬值,我想知道如何使用preg替代。这是我的代码,我需要替换{}标记 $template = ereg_replace('{USERNAME}', $info['username'], $template); $template = ereg_replace('{EMAIL}', $info['email'], $template); $template = ereg_replace('{KEY}', $info['key'], $template)

由于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,它将不起作用。

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


工作起来很有魅力。

我不知道ereg\u replace是如何工作的,但是preg\u 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{}{{{}"

谢谢你,伙计!作品perfectly@user2802518因此,将其标记为解决方案:)谢谢!“使用正则表达式和正则表达式。”---什么?我试图解释preg_replace使用正则表达式模块,所以您必须使用正则表达式进行搜索。什么是“正则表达式模块”?