【问题标题】:how to detect Json inside a string in php如何在php中检测字符串中的Json
【发布时间】:2012-11-01 16:30:13
【问题描述】:

我遇到了一个问题,我有一个包含完整描述的字符串以及一个包含一些 Id 的 json。如何将 Json 从字符串中取出并对其执行任何事件..

我的数据如下所示

The description of xxxxxxxxxxxxxxxxxxxxxxxxxx
[{"id":"613"},{"id":"614"},{"id":"615"}]

有什么方法可以让我获得完整的描述和 ID,以便我可以解码它们并在我想要的地方使用?

提前感谢您的支持

【问题讨论】:

  • 如果描述不总是只有一行或有任何其他适当的限制(例如不包含 { 使该字符始终成为第一个 JSON 字符),您可能必须使用蛮力解决方案。示例见stackoverflow.com/a/10574546/298479(用 JavaScript 编写,但您可以将其移植到 PHP)
  • 它们总是用换行符分隔吗?

标签: php arrays json


【解决方案1】:

试试这个

$string = 'The description of xxxxxxxxxxxxxxxxxxxxxxxxxx    [{"id":"613"},{"id":"614"},{"id":"615"}] asdasd';

if(false !== preg_match('/\[(.*)\]/', $string, $matches)) {
    for($n = 1; $n < count($matches); $n++) {
        $json_result = json_decode('['.$matches[$n].']', true);
        if(null === $json_result) {
            //cannot parse json
        }
        print_r($json_result);
    }
}

【讨论】:

    【解决方案2】:

    如果您的 json 在新行中,这将找到具有 JSON 代码的第一行!!!

    $string = 'The description of xxxxxxxxxxxxxxxxxxxxxxxxxx
    [{"id":"613"},{"id":"614"},{"id":"615"}]';
    $strings = explode("\n",$string);
    
    foreach($strings as $str){
        $json = json_decode($str,TRUE); //TRUE for array responde
        if(!empty($json)){
           break;
        }
    }
    
    var_dump($json);
    

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 2019-01-09
      • 2013-09-12
      • 2013-02-09
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多