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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13141406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:50:44  来源:igfitidea点击:

How to replace "\" using str_replace() in PHP?

php

提问by user1759682

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?

我可能做错了什么?

回答by sevenseacat

The backslash is actually escaping the closing quote in your string.

反斜杠实际上是在转义字符串中的结束引号。

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

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

回答by Baba

No sure why you are using str_replaceto remove \use

不知道你为什么要使用str_replace删除\使用

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

But if its just an example then

但如果它只是一个例子那么

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

Please Note that stripslashesonly remove backslashes not forward

请注意,stripslashes只删除反斜杠而不是向前

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

Outputs

输出

it's // Tuesday!

回答by Er.Sangeeta

Try and get the result:

尝试并得到结果:

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

$remove_slash = stripslashes($str);

print_r($remove_slash);

Output: it's Tuesday!

输出:今天是星期二!

回答by inhan

From the stripslashes()documentation:

stripslashes()文档:

Returns a string with backslashesstripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

返回一个去掉反斜杠的字符串。(\' 变成 ' 等等。)双反斜杠 (\\) 变成一个反斜杠 (\)。

So you shouldn't worry about the fwd. slashes.

所以你不应该担心 fwd。斜线。

回答by user2609583

With:

和:

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