handle special characters in strings

This commit is contained in:
Pekka Laiho 2020-06-16 20:15:57 +07:00
parent 034598cd71
commit ad70c6dbd0
3 changed files with 12 additions and 8 deletions

View File

@ -275,10 +275,6 @@ odd? | Return true if the argument is odd number (1, 3, 5, ...).
The project is easy to extend because it is trivial to add new functions whether the implementation is defined on the PHP or Lisp side. If the language ends up being used in the future, first plans are to add support for JSON serialization and a HTTP client. The project is easy to extend because it is trivial to add new functions whether the implementation is defined on the PHP or Lisp side. If the language ends up being used in the future, first plans are to add support for JSON serialization and a HTTP client.
## Known issues
Special characters such as `\"`, `\n` or `\r` are not handled/escaped correctly in strings yet.
## License ## License
[MIT](https://choosealicense.com/licenses/mit/) [MIT](https://choosealicense.com/licenses/mit/)

View File

@ -77,8 +77,13 @@ class Reader
} elseif ($a === 'null') { } elseif ($a === 'null') {
return null; return null;
} elseif (substr($a, 0, 1) === '"') { } elseif (substr($a, 0, 1) === '"') {
// string // string, handle special characters
return substr($a, 1, strlen($a) - 2); $a = substr($a, 1, -1);
$a = str_replace("\\\\", chr(0x7f), $a);
$a = str_replace("\\n", "\n", $a);
$a = str_replace("\\r", "\r", $a);
$a = str_replace("\\\"", "\"", $a);
return str_replace(chr(0x7f), "\\", $a);
} elseif (is_numeric($a)) { } elseif (is_numeric($a)) {
if (filter_var($a, FILTER_VALIDATE_INT) !== false) { if (filter_var($a, FILTER_VALIDATE_INT) !== false) {
return intval($a); return intval($a);

View File

@ -30,9 +30,12 @@ class Tokenizer
// Stop at first double quote // Stop at first double quote
if ($c == '"') { if ($c == '"') {
// If previous character is not a backslash
if (strlen($current) < 2 || substr($current, -2, 1) != "\\") {
$addCurrent(); $addCurrent();
$isString = false; $isString = false;
} }
}
} elseif ($isComment) { } elseif ($isComment) {
// Comments stop at first newline // Comments stop at first newline
if ($c == "\n" || $c == "\r") { if ($c == "\n" || $c == "\r") {