php preg_match_all不工作或不显示结果

jslywgbw  于 2023-03-07  发布在  PHP
关注(0)|答案(1)|浏览(167)

{"popUp":false,"token":"NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7"}这是JSON中的curl响应,我想从这个JSON响应中提取令牌。
我使用了preg_match_all函数,但它显示为空
这是我代码

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)

我想将令牌存储在$newtkn变量中,并在屏幕上回显它,该怎么做?

dwbf0jvd

dwbf0jvd1#

使用json_decode()可能更容易,如下所示:

$result = '{"popUp":false,"token":"NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7"}';

$arr = json_decode($result, true);

$newtkn = $arr['token'];

echo $newtkn; //NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7

或者,如果你更喜欢一个面向对象的答案:

$result = '{"popUp":false,"token":"NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7"}';

$obj = json_decode($result);

$newtkn = $obj->token;

echo $newtkn; //NS2938f08ubjk765vhjJBKJB78vhjeec1_m1_7

相关问题