Home » Php » How do you make a string in PHP with a backslash in it?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need a backslash to be a part of a string. How can I do it?

How to&Answers:

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 = 'abc2';
$string = "abc\012";

Answer:

Short answer:

Use two backslashes.

Long answer:

You can sometimes use a single backslash, but sometimes you need two. When you can use a single backslash depends on two things:

  • whether your string is surrounded by single quotes or double quotes and
  • the character immediately following the backslash.

If you have a double quote string the backslash is treated as an escape character in many cases so it is best to always escape the backslash with another backslash:

$s = "foo\bar"

In a single quoted string backslashes will be literal unless they are followed by either a single quote or another backslash. So to output a single backslash with a single quoted string you can normally write this:

$s = 'foo\bar'

But to output two backslashes in a row you need this:

$s = 'foo\\bar'

If you always use two backslashes you will never be wrong.

Answer:

You have to escape all backslashes like "c:\\windows\\".