Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 873
Seth Avatar asked Jan 21 '11 22:01

Seth


People also ask

How do I add a backslash at the end of a string in PHP?

PHP: addslashes() function The addslashes() function is used to add backslashes in front of the characters that need to be quoted. The predefined characters are single quote ('), double quote("), backslash(\) and NULL (the NULL byte).

How do you pass a backslash in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do I strip a slash in PHP?

The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

How remove forward and backward slash from string in PHP?

$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8"; $access_token = preg_replace('/\\\//', '/', $access_token);


2 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 = 'abc\012'; $string = "abc\\012"; 
like image 110
Mark Baker Avatar answered Oct 19 '22 08:10

Mark Baker


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.

like image 22
Mark Byers Avatar answered Oct 19 '22 07:10

Mark Byers