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.
## Known issues
Special characters such as `\"`, `\n` or `\r` are not handled/escaped correctly in strings yet.
## License
[MIT](https://choosealicense.com/licenses/mit/)

View File

@ -77,8 +77,13 @@ class Reader
} elseif ($a === 'null') {
return null;
} elseif (substr($a, 0, 1) === '"') {
// string
return substr($a, 1, strlen($a) - 2);
// string, handle special characters
$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)) {
if (filter_var($a, FILTER_VALIDATE_INT) !== false) {
return intval($a);

View File

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