0

I wanted to pass a file name, generated by a batch file, to a commandline php script as an argument. Of course, to access local files in Windows, you have to double the backslashes (c:\\blah\\yeah.txt). It's challenging because the back slash is an escape character.

$fName = $_GET["fileName"];                 // yields c:\blah\yeah.txt
$fName = ___TRANSFORM THE SLASHES HERE___;  //needs to be c:\\blah\\yeah.txt
$fh = fopen($fName, 'rb');
$feed = fread($fh, filesize($fName));
fclose($fh);

How do you do this using regex?

NOTE: I'm using $_GET because I wanted to use the parameter name rather than $argv[0]. See hamboy75's note here on the php website.

Josiah
  • 3,008
  • 1
  • 34
  • 45

1 Answers1

0

Use this regex: $fName = preg_replace('{\\\}','\\\\\\',$fName); You need 3 \'s to match 1 and 6 to match 2. Also, it won't work without curly brackets.

If someone wiser than me wants to explain the why, I'd appreciate it. I just wanted to save someone else some head scratching.

Josiah
  • 3,008
  • 1
  • 34
  • 45
  • 1
    Josiah, it's explained in [here]. (http://stackoverflow.com/questions/20818283/how-to-properly-escape-a-backslash-to-match-a-literal-backslash-in-single-quoted) – bitfhacker May 31 '14 at 23:47