How do you make a string in PHP with a backslash in it? [closed]

When the backslash \ does not escape the terminating quote of the string or otherwise create a valid escape sequence (in double quoted strings), then either of these work to produce one backslash:

$string = 'abc\def';
$string = "abc\def";
//
$string = 'abc\\def';
$string = "abc\\def";

When escaping the next character would cause a parse error (terminating quote of the string) or a valid escape sequence (in double quoted strings) then the backslash needs to be escaped:

$string = 'abcdef\\';
$string = "abcdef\\";

$string = 'abc\012';
$string = "abc\\012";

Leave a Comment