【问题标题】:php turn this syntax into object/arrayphp 将此语法转换为对象/数组
【发布时间】:2015-06-06 13:32:48
【问题描述】:

有没有办法转这个:

network={
    ssid="tele2-ssid-66577"
    #psk="testtest2"
    psk=8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
}

用php转换成对象或数组?

我试过 json_decode 没有结果。

---------- 更新:

最终目标是仅提取 psk 键,我只是认为将其转换为对象/数组将是最简单的事情,而不是干预正则表达式或摆弄字符串,但也许这是不可能的.. .

【问题讨论】:

  • 你如何以及从哪里得到这个?
  • 通过终端命令生成密码
  • 这个字符串是否带有 EOL ?
  • 我相信是这样,运行 exec() 只会返回最后一行的字符,即 } 所以 shell_exec 是检索整个内容所必需的
  • 我已经构建了一个将 JSON 值作为参数的方法,您可以将参数放入 Array 中吗?所以我可以给你链接。

标签: php arrays string object decode


【解决方案1】:

我通过正则表达式运行它,然后进行一些处理

$str = 'network={
    ssid="tele2-ssid-66577"
    #psk="testtest2"
    psk=8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
}';

$output = array();
if (preg_match_all('/(([^=]+)=\{|\s+([^#]+)=(.*))/', $str, $match) and sizeof($match[2]) > 2) {
    $output[$match[2][0]] = array();
    for ($i=1; $i<sizeof($match[2]); $i++) {
        $key = trim($match[3][$i]);
        $value = trim($match[4][$i]);

        // remove outer double quotes
        if (preg_match('/^"(.*)"$/', $value, $match2)) $value = $match2[1];

        // save
        $output[$match[2][0]][$key] = $value;
    }
}

print_r($output);

给出输出:

Array
(
    [network] => Array
        (
            [ssid] => tele2-ssid-66577
            [psk] => 8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
        )
)

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2019-09-13
    • 2021-01-28
    • 2018-10-29
    相关资源
    最近更新 更多