I took these sentences from the PHP manual:
'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'
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:
<?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) . '\'' . '</br>';
}
?>
The output is:
'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'
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.
(I have asked this question elsewhere recently but without a solution)
Thanks in advance.
Instead of meddling with
preg_replace(), consider usingvar_export()to print a “true copy” of the string:Output:
As you can see, sentence 3 and 4 are identical to PHP.