Search code examples
phpescaping

Escaping double backslash inside a string


Which is the correct way for escaping a double backslash in a PHP string? The following code output is identical:

echo "foo\\\bar";
echo "foo\\\\bar";

Output:

foo\\bar
foo\\bar

Solution

    • \b has no function, so will be displayed as such: \b.
    • \\ is an escaped backslash and is displayed as \.

    So two backslashes won't do because it will only display one. Three will be sufficient and four just means two escaped backslashes.

    So they're both correct, however, four backslashes is "safer", especially when what follows can vary. Also, you don't want to rely on \b having no function forever.