Search code examples
phpfunctionpreg-matchpreg-match-all

preg_match_all is not working or showing result


{"popUp":false,"token":"NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7"} This is curl response in JSON, and i want to extract token from this JSON response.

i used preg_match_all function but its showing null

here is my code

preg_match_all('/^"token":"\s*([^;]*)/mi', $result, $matches);
$token = array();
foreach($matches[1] as $item) {
    parse_str($item, $newtkn);
    $token = array_merge($token, $newtkn);
}
var_dump($newtkn)

i want to store that token in $newtkn variable and echo it on the screen how do i do that ?


Solution

  • Probably way easier to use json_decode() as it follows:

    $result = '{"popUp":false,"token":"NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7"}';
    
    $arr = json_decode($result, true);
    
    $newtkn = $arr['token'];
    
    echo $newtkn; //NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7
    

    Or if you prefer an oriented object answer:

    $result = '{"popUp":false,"token":"NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7"}';
    
    $obj = json_decode($result);
    
    $newtkn = $obj->token;
    
    echo $newtkn; //NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7