zhwatts zhwatts -4 years ago 145
PHP Question

php string backslash followed by digit

I have a variable that is set by a file path. The path is dynamically set based on date as such

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

notice the backslashes followed by digits. This is set by the server and I cannot alter it before it reaches my php file, however it seems to be causing those characters to encode, thus making my script break.

I've tried to use str_replace to change the backslashes to forward slashes but according to my understanding of the php manual on blackslashes, it is being encoded before the function has a chance to run.

My question is this:

Is there a way to change how php is reading that string? or is there a way I can alter it so that it becomes usable?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download