title: Decoder for backslash-escaped string
body: <p>What is the correct way in PHP to deal with decoding strings, such as these:</p>
  
  <pre><code>Test1 \\ Test2 \n Test3 \\n Test4 \abc
  </code></pre>
  
  <p>The desired output is:</p>
  
  <pre><code>Test \ Test2 (linebreak) Test3 \n Test4 abc
  </code></pre>
  
  <p>One thing I've tried was:</p>
  
  <pre><code>str_replace(array('\\\\','\\n','\\'), array('\\',"\n",''), $str);
  </code></pre>
  
  <p>But that doesn't work, because it will run the replacing twice, which causes:</p>
  
  <pre><code>\\n
  </code></pre>
  
  <p>To be decoded as a linebreak anyway.</p>
  
  <p>So I was thinking something like this:</p>
  
  <pre><code>$offset = 0;
  $str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
  while(($pos = strpos($str,'\\', $offset)) !== false) {
  
    $char = $str[$pos+1];
    if ($char=="n" || $char=="N") {
       // Insert a newline and eat 2 characters
       $str = substr($str,0,$pos-1) . "\n" . substr($str,$pos+2);
    } else {
       // eat slash
       $str = substr($str,0,$pos-1) . substr($str,$pos+1);
    }
    $offset=$pos+1;
  
  }
  </code></pre>
  
  <p>This seems to work, but I was wondering if there's maybe a built-in that does exactly this and I completely missed it, or a better/more compact way altogether to do this.</p>