Escaped Backslash Characters in PHP Single Quoted Strings
<p>I took these sentences from the PHP manual:</p>

<pre><code>'this is a simple string',
'Arnold once said: "I\'ll be back"',
'You deleted C:\\*.*?',
'You deleted C:\*.*?',
'This will not expand: \n a newline',
'Variables do not $expand $either'
</code></pre>

<p>I would like to echo them using PHP code, exactly as they appear, with escaped single quotes (like in the second sentence) and double backslashes (like in the third sentence). This is what I have so far:</p>

<pre><code>&lt;?php

$strings = array(
        'this is a simple string',
        'Arnold once said: "I\'ll be back"',
        'You deleted C:\\*.*?',
        'You deleted C:\*.*?',
        'This will not expand: \n a newline',
        'Variables do not $expand $either');

$patterns = array('~\\\'~', '~\\\\~');
$replacements = array('\\\\\'', '\\\\\\\\');

foreach($strings as $string)
{
        echo '\'' . preg_replace($patterns, $replacements, $string) . '\'' . '&lt;/br&gt;';
}
?&gt;
</code></pre>

<p>The output is:</p>

<pre><code>'this is a simple string'
'Arnold once said: "I\\'ll be back"'
'You deleted C:\\*.*?'
'You deleted C:\\*.*?'
'This will not expand: \\n a newline'
'Variables do not $expand $either'
</code></pre>

<p>but I would like to echo the strings exactly as they are listed in my code if possible. I am having trouble with double backslash characters (\). My second pattern ('~\\~') seems to replace both single and double backslashes. I also tried using addcslashes() with the same results.</p>

<p>(I have asked this question elsewhere recently but without a solution)</p>

<p>Thanks in advance.</p>
