Skip to content

Commit

Permalink
Use hex escaping for special characters in strings
Browse files Browse the repository at this point in the history
Apart from \0, using the \xHH notation is more typical.
  • Loading branch information
nikic committed Apr 25, 2021
1 parent f68e1a4 commit 6b409b9
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 11 deletions.
10 changes: 3 additions & 7 deletions lib/PhpParser/PrettyPrinter/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -999,13 +999,9 @@ protected function escapeString($string, $quote) {
}

// Escape other control characters
return preg_replace_callback('/([\0-\10\16-\37])(?=([0-7]?))/', function ($matches) {
$oct = decoct(ord($matches[1]));
if ($matches[2] !== '') {
// If there is a trailing digit, use the full three character form
return '\\' . str_pad($oct, 3, '0', \STR_PAD_LEFT);
}
return '\\' . $oct;
return preg_replace_callback('/[\x00-\x08\x0e-\x1f]/', function ($matches) {
$hex = dechex(ord($matches[0]));;
return '\\x' . str_pad($hex, 2, '0', \STR_PAD_LEFT);
}, $escaped);
}

Expand Down
8 changes: 4 additions & 4 deletions test/code/prettyPrinter/expr/stringEscaping.test
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ DOC;

-----
"\n\r\t\f\v\$\"\\";
"\0\1\2\3\4\5\6\7\10\t\n\v\f\r\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37";
"\0000\0001";
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";
"\x000\x001";
"äöü";
<<<DOC
@@{ "\n\r" }@@\t\f\v\$\\"\\
\0\1\2\3\4\5\6\7\10\t@@{ "\n" }@@\v\f@@{ "\r" }@@\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37
\0000\0001
\x00\x01\x02\x03\x04\x05\x06\x07\x08\t@@{ "\n" }@@\v\f@@{ "\r" }@@\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f
\x000\x001
äöü
DOC
;

0 comments on commit 6b409b9

Please sign in to comment.