简体   繁体   English

如何在PHP中使用str_replace()替换“\\”?

[英]How to replace “\” using str_replace() in PHP?

I would like to remove all back slashes from strings on my site. 我想从我网站上的字符串中删除所有反斜杠。 I do not wish to use strip_slashes(), because I want to keep forward slashes. 我不想使用strip_slashes(),因为我想保持正斜杠。

This is the code I am trying: 这是我正在尝试的代码:

echo str_replace("\", "", "it\'s Tuesday!");

I want to find the backslash in any given string and remove it. 我想在任何给定的字符串中找到反斜杠并将其删除。 But, this code is not working right. 但是,这段代码不正常。

Error: 错误:

syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

What could I be doing wrong? 我能做错什么?

The backslash is actually escaping the closing quote in your string. 反斜杠实际上是在字符串中转义结束引号。

Try echo str_replace("\\\\","","it\\'s Tuesday!"); 尝试echo str_replace("\\\\","","it\\'s Tuesday!");

No sure why you are using str_replace to remove \\ use 不确定为什么要使用str_replace来删除\\ use

echo stripslashes("it\'s Tuesday!");

But if its just an example then 但如果它只是一个例子那么

echo  str_replace("\\","","it\'s Tuesday!");

Please Note that stripslashes only remove backslashes not forward 请注意, stripslashes只删除不向前的反斜杠

echo stripslashes("it\'s \\ \\  // Tuesday!");

Outputs 输出

it's // Tuesday!

Try and get the result: 尝试并获得结果:

$str = "it\'s Tuesday!";

$remove_slash = stripslashes($str);

print_r($remove_slash);

Output: it's Tuesday! 输出:星期二!

From the stripslashes() documentation: 来自stripslashes()文档:

Returns a string with backslashes stripped off. 返回带有反斜杠的字符串。 (\\' becomes ' and so on.) Double backslashes (\\\\) are made into a single backslash (\\). (\\'变为'等等。)双反斜杠(\\\\)被制成一个反斜杠(\\)。

So you shouldn't worry about the fwd. 所以你不应该担心前任。 slashes. 斜杠。

With: 附:

echo str_replace("\'", "'", "it\'s Tuesday!");
// It's Tuesday!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM