如果我使用单引号,str_replace 函数不会替换字符串

发布于 2024-09-04 09:39:52 字数 240 浏览 4 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

殤城〤 2024-09-11 09:39:52

有一个区别'" 之间。去掉单引号字符串内的 \

编辑:为了澄清,双引号字符串做了一些扩展(请参阅链接),而单引号的 $ 需要在双引号字符串内用 \ 转义,但在单引号字符串中则不需要。在后一种情况下,它实际上会导致 \$

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 \$.

星軌x 2024-09-11 09:39:52

美元符号和大括号在双引号字符串内具有特殊含义。 $ 用于将变量的内容直接放入字符串中。 {} 用于包装 PHP 变量,以防它们的含义不明确。

例如,"$hello" 会将变量 $hello 的内容放入字符串中,而 "{$hell}o" 会将变量 $hello 的内容放入字符串中将变量 $hell 的内容写入字符串,后跟文字字母 o。

单引号根本没有这个(为了简单起见,在引用更复杂的字符串时通常更可取)。因此 '{$hell}o' 将是一个包含实际字符 {$hell}o 的字符串。

有点不清楚您要替换的确切字符串。要将文字 {x+$v} 替换为 {x-$v},然后使用:

str_replace('{x+$v}', '{x-$v}', $this->introtext);

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:

str_replace('{x+$v}', '{x-$v}', $this->introtext);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文