Relm Relm - 3 months ago 10
JSON Question

PHP : How to decode json string with quotes

A server returns a string like this:

string(150) ""\"{ 'success': false,
'message': Email address already registered,
'error': { 'code': 100,
'message': 'Email address already registered!' }}\"""


Calling json_decode on the result doesn't change the string into array, it just remains a string.

How can I fix this string to be converted to a PHP array?

Answer

If you still need to get values of success and message keys from that string - use the following approach with preg_match_all and array_combine functions:

$str = "\"{ 'success': false, 
'message': Email address already registered, 
'error': { 'code': 100, 
           'message': 'Email address already registered!' }}\"";

preg_match_all("/'(?<k>success|message)':(?<v>[^,]+)(?=,)/", $str, $matches);
$result = array_combine($matches['k'], $matches['v']);

print_r($result);

The output:

Array
(
    [success] =>  false
    [message] =>  Email address already registered
)