title: Replacing single backslashes with double backslashes in php
body: <p>I came across a strange problem in my PHP programming. While using the <code>backtrace</code> function to get the last file the PHP compiler was working with. It would give it to me the path using backslashes. I wanted to store this string in the database, but MySQL would remove them; I'm assuming it was thinking I wanted to escape them. </p>
  
  <p>So <code>C:\Path\To\Filename.php</code> would end up <code>C:PathToFileName.php</code> in the database. When I posted this question to Google, I found many others with the same problem but in many different situations. People always suggested something like:</p>
  
  <pre><code>$str = '\dada\dadda';
  var_dump(str_replace('\', '\\', $str)); 
  </code></pre>
  
  <p>The problems with this is, even if you put it into a loop of some kind, is that you just keep replacing the first <code>\</code> with <code>\\</code>. So it starts off like <code>\</code> then <code>\\\</code> then <code>\\\\\</code> then <code>\\\\\\\</code> then <code>\\\\\\\\\</code> etc... Until it fills the memory buffer with this huge string. </p>
  
  <p>My solution to this problem, if anyone else has it is: </p>
  
  <pre><code>//$file = C:\Path\To\Filename.php
  
  //Need to use \\ so it ends up being \
  $fileArray = explode("\\", $file);
  
  //take the first one off the array
  $file = array_shift($fileArray);
  
  //go thru the rest of the array and add \\\\ then the next folder
  foreach($fileArray as $folder){
      $file .= "\\\\" . $folder;
  }
  
  echo $file
  //This will give you C:\\Path\\To\\Filename.php
  </code></pre>
  
  <p>So when it's stored in the database, it will appear to be <code>C:\Path\To\Filename.php</code>. </p>
  
  <p>If anyone else has a better solution to this, I'm all ears. </p>