0

我有这个字符串:

$string='我的字符串 [{Text_001}] 我的字符串 [{Text_002}] ';

我想用 $something 替换 preg_replace [{something}](例如:[{Text_001}] -> $Text_001)。

我的 preg_replace 有一个错误:

$string = preg_replace('/([{.+?)+(}])/i', "$1", $string);

4

3 回答 3

0

利用:

<?php
$string='My String [{Text_001}] My String [{Text_002}] ';

$string = preg_replace("~".preg_quote('[{')."(.*?)".preg_quote('}]')."~","something", $string);

echo $string;
?>

替换后[{something}]的输出something

My String something My String something 
于 2013-10-07T08:08:47.210 回答
0

\[并且{在 PCRE 中具有特殊含义(加上您的正则表达式格式错误)。只是逃避他们:

$string = preg_replace('/(\\[\\{(.+?)\\}\\])/i', "$1", $string);
于 2013-10-07T07:59:12.867 回答
0
$string = preg_replace('~\[\{(.+?)\}\]~', "\$$1", $string);
# My String $Text_001 My String $Text_002

解释例子

于 2013-10-07T07:59:27.273 回答