2

I don't really get the following...

// array to encode
$a = ['regex' => '\/\+\/'];

// decoding an encoded array works
print_r(json_decode(json_encode($a), true));

// encoded array
echo json_encode($a);

// trying to decode the before encoded string doesn't work
print_r(json_decode('{"regex":"\\\/\\+\\\/"}', true));
echo json_last_error_msg();

The last error message says Syntax error. Shouldn't I be able to easily decode a simple encoded string?

I know that the problem is in the backslashes but I won't want to do any magic string replacement or regex to get the decoding working. Just want to understand where goes what wrong and what's a best practice for this kind of situations?

I'm using PHP version 5.5.9

1
  • Hmm. At same php version I've got invalid string sequence error Commented Sep 14, 2015 at 16:38

2 Answers 2

4

Found something thanks to that answer : https://stackoverflow.com/a/10929508/1685538

If instead of taking the string outputted by echo, you use var_export(json_encode($a)); (documentation), it gives you {"regex":"\\\\\\/\\\\+\\\\\\/"}

print_r(json_decode('{"regex":"\\\\\\/\\\\+\\\\\\/"}', true)); gives the expected result :

Array
(
    [regex] => \/\+\/
)

with no errors.

Sign up to request clarification or add additional context in comments.

1 Comment

If it is all you needed, please consider accepting an answer @va5ja
1

The problem is that using backslashes in PHP code string literals is subject to PHP's backslash escaping rules. You need to additionally escape the backslashes so they are preserved inside the PHP string:

print_r(json_decode('{"regex":"\\\\\\/\\\\+\\\\\\/"}', true));

Contrast with:

echo '{"regex":"\\\/\\+\\\/"}'; 
//    {"regex":"\\/\+\\/"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.