开发者

str_replace function wont replace string if i use single quotes

I using php's str_replace function to replace some text. Example below.

str_replace("{x+{\$v}}", "{x-{\$v}}", $this->introt开发者_开发百科ext);

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?


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜