【问题标题】:Split a string with certain scheme, is this a bad practice?使用特定方案拆分字符串,这是一种不好的做法吗?
【发布时间】:2013-04-07 16:47:52
【问题描述】:

我有一个看起来像这样的字符串

[{ "title":"","comment":"","size":"18.298","name":"logo.png",
"filename":"fu_mucqjrfifpadsw8","ext":"png" }]

我想从中获取 filename.ext。对我来说,看起来我可以比以下更容易做到这一点(这确实有效,但似乎是不好的做法 - 或者是吗?)

我目前是如何提取它的:

$logo = explode(':',$string);
$ext = str_replace('"', "", $logo[6]);
$ext = str_replace(' }]', "", $ext);
$logo = explode(',',$logo[5]);
$logo=str_replace('"', "", $logo[0]);

【问题讨论】:

    标签: php arrays string


    【解决方案1】:

    它看起来像 JSON 数据。您可以使用 php 的json_decode 获取一个数组然后索引该数组。

    $string = '[{ "title":"","comment":"","size":"18.298","name":"logo.png","filename":"fu_mucqjrfifpadsw8","ext":"png" }]';
    $data = json_decode($string, true);
    // Access filename field
    $data[0]['filename'];
    

    【讨论】:

      【解决方案2】:

      这是可怕的做法。您的数据是 JSON 格式,因此您应该使用json_decode 将其转换为 PHP 变量,然后导航到您需要的信息。

      例如获取文件名+扩展名:

      $data = json_decode($string, true);
      $filename = $data[0]['filename'];
      $ext = $data[0]['ext'];
      
      $allTogether = $filename.'.'.$ext;
      

      【讨论】:

      • 这就是我问的原因。我不知道它是 json ......试图用谷歌搜索它,但你如何用谷歌搜索这样的字符串结构:D
      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多