如果我使用单引号,str_replace 函数不会替换字符串
我使用 php 的 str_replace 函数来替换一些文本。下面的例子。
str_replace("{x+{\$v}}", "{x-{\$v}}", $this->introtext);
str_replace('{x+{\$v}}', '{x-{\$v}}', $this->introtext);
在第一种情况下,它会替换文本,但在第二种情况下,它不会这样做。两者有什么区别?
I using php's str_replace function to replace some text. Example below.
str_replace("{x+{\$v}}", "{x-{\$v}}", $this->introtext);
str_replace('{x+{\$v}}', '{x-{\$v}}', $this->introtext);
In first case it replace text, but in second case it is not doing so. What is difference between two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个区别在
'
和"
之间。去掉单引号字符串内的\
。编辑:为了澄清,双引号字符串做了一些扩展(请参阅链接),而单引号的
$
需要在双引号字符串内用\
转义,但在单引号字符串中则不需要。在后一种情况下,它实际上会导致\$
。There is a difference between
'
and"
. Get rid of the\
inside the single-quoted string.EDIT: To clarify, a double-quoted string does some expansion (see the link), whereas the single-quoted one does not.
$
needs to be escaped with\
inside double-quoted strings, but not in single-quoted strings. In the latter case, it would literally result in\$
.美元符号和大括号在双引号字符串内具有特殊含义。
$
用于将变量的内容直接放入字符串中。{}
用于包装 PHP 变量,以防它们的含义不明确。例如,
"$hello"
会将变量$hello
的内容放入字符串中,而"{$hell}o"
会将变量$hello
的内容放入字符串中将变量$hell
的内容写入字符串,后跟文字字母 o。单引号根本没有这个(为了简单起见,在引用更复杂的字符串时通常更可取)。因此
'{$hell}o'
将是一个包含实际字符{$hell}o
的字符串。有点不清楚您要替换的确切字符串。要将文字
{x+$v}
替换为{x-$v}
,然后使用:The dollar sign and curly braces have special meanings when inside double-quoted strings.
$
is used to put content from a variable directly into a string.{}
is used to wrap PHP variables in case their meaning is ambiguous.For example
"$hello"
would put the contents of the variable$hello
into the string, whereas"{$hell}o"
would put the contents of the variable$hell
into the string, followed by the literal letter o.Single quotes don't have this at all (and are generally preferable when quoting more complex strings, for simplicity). So
'{$hell}o'
would be a string containing the actual characters{$hell}o
.It's a little unclear what exact strings you are trying to replace. To replace the literal
{x+$v}
with{x-$v}
then use: