你如何在 PHP 中创建一个带有反斜杠的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4764729/
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
How do you make a string in PHP with a backslash in it?
提问by Seth
I need a backslash to be a part of a string. How can I do it?
我需要一个反斜杠才能成为字符串的一部分。我该怎么做?
回答by Mark Baker
When the backslash \
does not escape the terminating quote of the string or otherwise create a valid escape sequence (in double quoted strings), then either of these work to produce one backslash:
当反斜杠\
没有转义字符串的终止引号或以其他方式创建有效的转义序列(在双引号字符串中)时,这些方法中的任何一个都会产生一个反斜杠:
$string = 'abc\def';
$string = "abc\def";
//
$string = 'abc\def';
$string = "abc\def";
When escaping the next character would cause a parse error (terminating quote of the string) or a valid escape sequence (in double quoted strings) then the backslash needs to be escaped:
当转义下一个字符会导致解析错误(字符串的终止引号)或有效的转义序列(在双引号中)时,需要转义反斜杠:
$string = 'abcdef\';
$string = "abcdef\";
$string = 'abc2';
$string = "abc\012";
回答by Mark Byers
Short answer:
简短的回答:
Use two backslashes.
使用两个反斜杠。
Long answer:
长答案:
You can sometimes use a single backslash, but sometimes you need two. When you can use a single backslash depends on two things:
有时您可以使用一个反斜杠,但有时您需要两个。何时可以使用单个反斜杠取决于两件事:
- whether your string is surrounded by single quotes or double quotes and
- the character immediately following the backslash.
- 您的字符串是否被单引号或双引号包围,并且
- 紧跟在反斜杠后面的字符。
If you have a double quote string the backslash is treated as an escape character in many cases so it is best to always escape the backslash with another backslash:
如果您有双引号字符串,反斜杠在许多情况下被视为转义字符,因此最好始终使用另一个反斜杠转义反斜杠:
$s = "foo\bar"
In a single quoted string backslashes will be literal unless they are followed by either a single quote or another backslash. So to output a single backslash with a single quoted string you can normally write this:
在单引号字符串中,反斜杠将是文字,除非它们后跟单引号或另一个反斜杠。因此,要使用单引号字符串输出单个反斜杠,您通常可以这样写:
$s = 'foo\bar'
But to output two backslashes in a row you need this:
但是要连续输出两个反斜杠,您需要这样做:
$s = 'foo\\bar'
If you always use two backslashes you will never be wrong.
如果你总是使用两个反斜杠,你永远不会错。
回答by Dogbert
You have to escape all backslashes like "c:\\windows\\"
.
您必须转义所有反斜杠,例如"c:\\windows\\"
.