Question

$backslash = '\\\\';
echo $backslash.$backslash;

would print two backslashes, while I'd expect it to print four.

Also,

$backslash = '\\';
echo $backslash.$backslash;

would only print one.

Why is that?


EDIT: Sorry for wasting your time.
The problem was I didn't actually echo it but instead returned the stored the value in a variable $escaped, which I then did other stuff with that actually caused the problem.

Was it helpful?

Solution

That's as expected. '-quoted strings have only two meta-characters which need to be escaped within them: ' and \. The ' has to be escaped, or you'd terminate the string early, and since \ itself is the escape character, it has to be escaped as well.

e.g.

<?php
$foo = '\\\';
echo $foo;

when executed will produce:

PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE in test.php on line 3

because the first two \ escape each other, becoming a single literal \ inside the string, and the 3rd \ escapes the ', causing the string to run off the end of the line and make the echo $foo PART of the string.

I cannot reproduce your second example. $foo = '\\'; will assign a SINGLE backslash to the string, and since you're printing out the variable twice, SHOULD get \\ as your output.


followup: with this code:

$two_slashes = '\\';
$four_slashes = '\\\\';
echo $two_slashes . $two_slashes . "\n";
echo $four_slashes . $four_slashes . "\n";

I get:

\\
\\\\

as output, as expected. This is on PHP 5.3.3 (Redhat enterprise 65.3)

OTHER TIPS

$backslash = '\\\\';
echo $backslash.$backslash;

output = \\\\

$backslash = '\\';
echo $backslash.$backslash;

output=\\

what's the problem?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top