PHP preg_replace 当我在替换中使用 { 时不起作用
PHP preg_replace not working when I use { in the substitution
由于某些原因,当替换包含花括号 {}
.
时,preg_replace
不起作用
如果原行是:
$Original_Line = "new_Journey('Iceland', {character: 'lidenbrock'}, {author : 'verne', destination : 'snæfellsjökull'})";
并且替换(在模式匹配之后)是:
new_Journey('', [, ])
给出以下 pattern-match/substitution:
$Replacement_Line = preg_replace("/new_Journey\(\'([^\']+)\'\,\s*\{([^\}]+)\}\,\s*\{([^\}]+)\}\)\;/", "new_Journey('', [, ])", $Original_Line);
输出是正确的(尽管使用方括号 []
而不是大括号 {}
):
new_Journey('Iceland', [author : 'verne', destination : 'snæfellsjökull', character: 'lidenbrock']);
但是,如果替换使用大括号 {}
而不是方括号 []
,如下所示:
new_Journey('', {, })
输出错误:
Parse error: syntax error, unexpected '3' (T_LNUMBER),
expecting variable (T_VARIABLE) or '{' or '$' in [...][...] on
line 5
我应该在替换中转义大括号 {}
吗?如果是,怎么做?
必须对 $
进行转义,因为 PHP 正在尝试将 </code> 扩展为变量,但 PHP 中的变量名称不能只是数字。</p>
<pre><code>"new_Journey('', {$3, $2})"
大括号而不是双引号字符串在 PHP 中有一些明确的用途,所以在你的情况下,可能是 PHP 认为你想要声明一个变量,当它看到打开花括号,因为您可以执行以下操作:
$var = "bananas";
$test = "{$var} are yummy" // Will execute: bananas are yummy
您可以将整个字符串替换为单引号并转义 </code>,如下所示:</p>
<pre><code>'new_Journey(\'\', {, })'
由于上述解释不适用于单引号。
由于某些原因,当替换包含花括号 {}
.
preg_replace
不起作用
如果原行是:
$Original_Line = "new_Journey('Iceland', {character: 'lidenbrock'}, {author : 'verne', destination : 'snæfellsjökull'})";
并且替换(在模式匹配之后)是:
new_Journey('', [, ])
给出以下 pattern-match/substitution:
$Replacement_Line = preg_replace("/new_Journey\(\'([^\']+)\'\,\s*\{([^\}]+)\}\,\s*\{([^\}]+)\}\)\;/", "new_Journey('', [, ])", $Original_Line);
输出是正确的(尽管使用方括号 []
而不是大括号 {}
):
new_Journey('Iceland', [author : 'verne', destination : 'snæfellsjökull', character: 'lidenbrock']);
但是,如果替换使用大括号 {}
而不是方括号 []
,如下所示:
new_Journey('', {, })
输出错误:
Parse error: syntax error, unexpected '3' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' in [...][...] on line 5
我应该在替换中转义大括号 {}
吗?如果是,怎么做?
必须对 $
进行转义,因为 PHP 正在尝试将 </code> 扩展为变量,但 PHP 中的变量名称不能只是数字。</p>
<pre><code>"new_Journey('', {$3, $2})"
大括号而不是双引号字符串在 PHP 中有一些明确的用途,所以在你的情况下,可能是 PHP 认为你想要声明一个变量,当它看到打开花括号,因为您可以执行以下操作:
$var = "bananas";
$test = "{$var} are yummy" // Will execute: bananas are yummy
您可以将整个字符串替换为单引号并转义 </code>,如下所示:</p>
<pre><code>'new_Journey(\'\', {, })'
由于上述解释不适用于单引号。