为什么在PHP中3个反斜杠等于4个反斜杠? [英] why 3 backslash equal 4 backslash in php?

查看:233
本文介绍了为什么在PHP中3个反斜杠等于4个反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php
$a='/\\\/';
$b='/\\\\/';
var_dump($a);//string '/\\/' (length=4)
var_dump($b);//string '/\\/' (length=4)
var_dump($a===$b);//boolean true
?>

为什么在PHP中带有3个反斜杠的字符串等于该字符串?

Why is the string with 3 backslashes equal to the string with 4 backslashes in PHP?

我们可以在正则表达式中使用3反斜杠版本吗?

And can we use the 3-backslash version in regular expression?

PHP参考说,我们必须使用4个反斜杠.

The PHP reference says we must use 4 backslashes.

注意: 单引号和双引号的PHP字符串具有反斜杠的特殊含义.因此,如果必须将\与正则表达式\\匹配,则必须在PHP代码中使用"\\\\"'\\\\'.

Note: Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

推荐答案

$b='/\\\\/';

php逐个字符地解析字符串文字(或多或少).第一个输入符号是正斜杠.结果是(解析步骤的)结果中的正斜杠,并且输入符号(一个字符,/)从输入中移出.
下一个输入符号是反斜杠.它从输入中获取,并检查下一个字符/符号.这也是一个反斜杠.这是一个有效的组合,因此第二个符号也从输入中获取,并且结果是一个单斜杠(对于两个输入符号).
第三个和第四个反斜杠相同.
最后一个输入符号(在文字内)是结果中的正斜杠->正斜杠.
-> /\\/

php parses the string literal (more or less) character by character. The first input symbol is the forward slash. The result is a forward slash in the result (of the parsing step) and the input symbol (one character, the /) is taken away from the input.
The next input symbol is a backslash. It's taken from the input and the next character/symbol is inspected. It's also a backslash. That's a valid combination, so the second symbol is also taken from the input and the result is a single blackslash (for both input symbols).
The same with the third and fourth backslash.
The last input symbol (within the literal) is the forwardslash -> forwardslash in the result.
-> /\\/

现在输入带有三个反斜杠的字符串:

Now for the string with three backslashes:

$a='/\\\/';

php查找"第一个斜杠,下一个字符为黑杠-这是一个有效的组合,导致结果中有一个单个斜杠,而输入文字中的两个字符均被使用. php然后查找"第三个反斜杠,下一个字符为正斜杠,这不是有效的组合.因此,结果是一个单斜杠(因为php喜欢并原谅您....),并且从输入中仅提取了一个字符. 下一个输入字符是正斜杠,导致结果中的正斜杠.
-> /\\/

php "finds" the first blackslash, the next character is a blackslash - that's a valid combination resulting in one single blackslash in the result and both characters in the input literal taken. php then "finds" the third blackslash, the next character is a forward-slash, this is not a valid combination. So the result is a single blackslash (because php loves and forgives you....) and only one character taken from the input. The next input character is the forward-slash, resulting in a forwardslash in the result.
-> /\\/

=>两个文字都编码相同的字符串.

=> both literals encode the same string.

这篇关于为什么在PHP中3个反斜杠等于4个反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆