Tuesday, 22 January 2019

PHP: regex in JSON causes problem for json_decode?

I have some regular expressions in my JSON, which doesn't seem to be a problem when I test my JSON on an online JSON validator. However, when I take that JSON string and try to json_decode() in PHP, I get a JSON_ERROR_SYNTAX.

Any ideas why? And how do I solve this?

Sample code:

<?php

    $json = <<<EOD
{
  "regex": [
    "Hello\s+World"
  ]
}
EOD;

json_decode($json);

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
}

The problem is in the \s. Changing it to \\s doesn't help.



from PHP: regex in JSON causes problem for json_decode?

No comments:

Post a Comment