Improve heuristic for escaping in single quoted strings

It is idiomatic to not escape backslashes if they are followed by
a non-special character.
This commit is contained in:
Nikita Popov 2022-07-24 22:56:44 +02:00
parent 646b490735
commit cf0cd6003e
2 changed files with 12 additions and 3 deletions

View File

@ -997,7 +997,12 @@ class Standard extends PrettyPrinterAbstract
}
protected function pSingleQuotedString(string $string) {
return '\'' . addcslashes($string, '\'\\') . '\'';
// It is idiomatic to only escape backslashes when necessary, i.e. when followed by ', \ or
// the end of the string ('Foo\Bar' instead of 'Foo\\Bar'). However, we also don't want to
// produce an odd number of backslashes, so '\\\\a' should not get rendered as '\\\a', even
// though that would be legal.
$regex = '/\'|\\\\(?=[\'\\\\]|$)|(?<=\\\\)\\\\/';
return '\'' . preg_replace($regex, '\\\\$0', $string) . '\'';
}
protected function escapeString($string, $quote) {

View File

@ -47,6 +47,8 @@ b';
'a\'b';
'a\b';
'a\\';
'a\\\\b';
'a\\\'b';
// strings (double quoted)
"a";
@ -122,8 +124,10 @@ FALSE;
'a
b';
'a\'b';
'a\\b';
'a\b';
'a\\';
'a\\\\b';
'a\\\'b';
// strings (double quoted)
"a";
"a\nb";