Use hex escaping for special characters in strings

Apart from \0, using the \xHH notation is more typical.
This commit is contained in:
Nikita Popov 2021-04-25 21:22:15 +02:00
parent f68e1a43ff
commit 6b409b96bb
2 changed files with 7 additions and 11 deletions

View File

@ -999,13 +999,9 @@ class Standard extends PrettyPrinterAbstract
}
// 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);
}

View File

@ -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
;