Hi friends can any one give clear explanation for this i could'nt get clearly why single backslashes where displaying in s and double slash in the s1,s2.
$s = "A backslash: \\ ";
$s1 = preg_replace("/\\\\/", "\\\\\\", $s);
$s2 = preg_replace("/\\\\/", "\\\\\\\\", $s);
echo "s : $s \n";
echo "s1: $s1 \n";
echo "s2: $s2 \n";
------------------
Output:
s : A backslash: \
s1: A backslash: \\
s2: A backslash: \\
About backslash
Moderator: General Moderators
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Re: About backslash
With 95% certainty....
In the search of preg_replace(), \\\\ is the same as a single backslash since you escape once for PHP, and again for the regex engine. In the replacement you've got the same situation, except you need escape *again* so the value returned back for PHP is correctly escaped. Therefore, \\\\\\\\ is the same as a single backslash in the replacement (because you read it as \\ (escape) \\ (backslash) \\ (escape) \\ (backslash)).
s is fairly obvious (I hope).
s1 is a bit of a trick since the trailing backslash is syntactically fine for PHP, yet it doesn't escape anything so PHP interprets it as backslash (see note below).
s2 follows exactly the same rules I explained above.
Is this a computer science course question? If it is it's about as crazy as some of the puzzles in the Java Puzzlers book! Lots of escaping and weird behaviour
NOTE: PHP treats backslashes which don't escape anything just like an escaped backslash: Try the following:
<?php
echo "a \ b"; //Note the whitespace either side of the \
?>
EDIT | I haven't used the
In the search of preg_replace(), \\\\ is the same as a single backslash since you escape once for PHP, and again for the regex engine. In the replacement you've got the same situation, except you need escape *again* so the value returned back for PHP is correctly escaped. Therefore, \\\\\\\\ is the same as a single backslash in the replacement (because you read it as \\ (escape) \\ (backslash) \\ (escape) \\ (backslash)).
s is fairly obvious (I hope).
s1 is a bit of a trick since the trailing backslash is syntactically fine for PHP, yet it doesn't escape anything so PHP interprets it as backslash (see note below).
s2 follows exactly the same rules I explained above.
Is this a computer science course question? If it is it's about as crazy as some of the puzzles in the Java Puzzlers book! Lots of escaping and weird behaviour
NOTE: PHP treats backslashes which don't escape anything just like an escaped backslash: Try the following:
<?php
echo "a \ b"; //Note the whitespace either side of the \
?>
EDIT | I haven't used the
Code: Select all
tags in this post due to the backslashes being majorly broken in our GeSHi mod right now.