I know PHP unescape a string as it's outputted. But I don't understand why
echo "\\\/";
generates the result
\\/
Anybody has idea?
Mh, I guess the easiest way to understand this is by looking at a view examples:
echo "/"; = /
echo "//"; = //
echo "///"; = ///
echo "\"; = syntax error
echo "\\"; = \
echo "\""; = "
echo "\\\" = syntax error
echo "\\\/"; = \\/
Why? Well \ is used for escaping. The last example is escaping \ with \\ and / with \/. Although / doesn't need any escaping it doesn't hurt.
You may wonder why echo "\\\" fails. But if you pay close attention you will notice that \\ is fine but then the third \ is considered as escape for the " at the end of the string which obviously is not supposed to get escaped hence the syntax error.
A backslash is a special character in PHP string literals. It is used to escape characters. For example, if you want to write a quote inside a quoted string, it needs to be escaped to avoid ambiguous/incorrect syntax:
echo "\""; // (Because otherwise, WTF exactly would """ mean?!)
Since the backslash is a special character, there needs to be a way to make it "non special" to avoid its special properties. If you want to write a single backslash in a string, you need to escape it:
echo "\\"; // (Because "\" would be a syntax error, since the " would be escaped.)
So in "\\\/", there's one escaped backslash (\\ → \), and then there's another single backslash. Since that second (third) backslash is not followed by any ambiguous character, it's just taken as is (i.e. \/ doesn't mean anything special, so it just means "\/"). So you've got three actual characters in that string: \, \ and /.
Note that this would be a syntax error:
echo "\\\";
Because the first pair is one backslash, followed by \", which is an escaped ", and then no "real" " afterwards to end the string.
If the character following \ does not represent a valid escape sequence then it will be left as-is.
The pattern \\ is a valid escape sequence so it is replaced with a single \.
The pattern \/ is not a valid escape sequence, so it is left alone.
The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.
For example, if you want to match a "*" character, you write "*" in the pattern. This applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\".
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.
echoing and what are you seeing?