Question

It is not uncommon to have to put a path to a file or directory in a string in a program or script’s code. This isn’t usually a problem with paths on *nix systems since they use forward slashes which usually does not need to be escaped in most languages, but Windows uses back slashes for paths which usually do need to be escaped in most languages.

With C(++), you usually do have to escape the slashes of a path in a string because most compilers will emit a warning if you don’t, but I have seen other code, particularly PHP scripts, which do not escape them. For example, I have seen countless examples of configuration files containing lines similar to this:

static $storageDir = 'C:\webgrind\tmp';

Ostensibly you must escape such paths, and I did consider that maybe they were written by people who were not actually using Windows and simply extrapolating configuration data from Linux to Windows without actually testing it, but if that were the case, then the code should fail, yet it seems that it often works.

So do you have to escape paths in strings in code? I’m asking mostly about PHP because that’s where I’ve personally seen this happen the most, but I’m open to other/universal answers as well.

Was it helpful?

Solution 3

Single quotes inhibit all escape sequences other than \\ and \', so there is no need to escape backslashes within them unless it appears as the final character in the string literal.

OTHER TIPS

Single quoted strings in PHP do not need the double escaping. Unlike double quoted strings where a lowercase letter behind a singular backslash could spell trouble.

However in single quoted strings, the backslash still can escape itself.

'abc\\abc' == 'abc\abc'

Speaking of paths particularly, forward slashes will do as well

'C:/webgrind/tmp'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top