How to Make a String in PHP with a Backslash in It

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

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";

Backslashes breaking string in PHP

The \ is special character, that says: 'The next character has special meaning'.

So if you want to dispaly \ you should write... \\ to get one \ in output

php string backslash followed by digit

The backslash within the string $str is escaping the character immediately following it, you can prevent this behaviour by using single quotes, or; you can escape the backslash (wait for it...) by using a backslash.

echo $str = "IMAGES\2016\08\01\NM.jpg";

Result: IMAGES?68\NM.jpg

echo $str = "IMAGES\\2016\\08\\01\\NM.jpg";

Result: IMAGES\2016\08\01\NM.jpg

Aside: You could use str_replace or preg_replace to replace each single backslash with two backslashes.

Php how to add backslash inside array of strings

Some info was missing which I got after discussion.

They are manually replacing a lot of characters before returning json. Out of them they also include [ => "[ and ] => ]" due to their backend implications.

A simple json_encode was solution for this along with skipping those character replacement for specific this key.

Find the occurrence of backslash in a string

For something simple as this, you don't need a regular expression. A string function like strpos() should be enough:

if (strpos('aud\ios', '\\') !== FALSE) {
// String contains '\'
}

Note that you need to escape the backslash here. If you simply write \, then PHP considers it as an escape sequence and tries to escape the character that follows. To avoid this, you need to escape the escape using another backslash: \\.

As for matching a literal backslash using a preg_* function, you'll need to use \\\\ instead of a single \.

From the PHP manual documentation on Escape Sequences:

Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

So your code would look like:

preg_match('/\\\\/', $string); // Don't use this though

where:

  • / - starting delimiter
  • \\\\ - matches a single literal \
  • / - ending delimiter

For additional information about this, see:

  • How to properly escape a backslash to match a literal backslash in single-quoted and double-quoted PHP regex patterns


Related Topics



Leave a reply



Submit