代码之家  ›  专栏  ›  技术社区  ›  ondrobaco

php将特定字符串转换为数组值

  •  2
  • ondrobaco  · 技术社区  · 16 年前

    我从服务器得到以下响应:

    OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235 OK: 0; Sent queued message ID: 9589936487b8d0a1 SMSGlobalMsgID:6141138716371692 
    

    等等

    这只是一个没有回车符的长字符串,我完全按照收到的格式复制了它。

    这是重复的模式:

    OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235
    

    我想把它转换成如下的数组:

    Array
    (
        [0] => Array
               [1] => OK
               [2] => 0
               [3] => e3674786a1c5f7a1
               [4] => 6162865783958235
    
        [1] => Array
               [1] => OK
               [2] => 0
               [3] => 9589936487b8d0a1
               [4] => 6141138716371692 
    )
    

    你会怎么做?我感谢你的意见。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Pascal MARTIN    16 年前

    $str = <<<STR
    OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235
    OK: 0; Sent queued message ID: 9589936487b8d0a1 SMSGlobalMsgID:6141138716371692
    STR;
    


    解决办法是 explode

    $lines = explode("\n", $str);
    

    在评论和评论编辑之后编辑

    考虑到你收到的数据只有一行,你必须找到另一种方法来分割它 (我认为拆分数据和处理“行”比一次处理一大块数据更容易) .

    $str = <<<STR
    OK: 0; Sent queued message ID: e3674786a1c5f7a1 SMSGlobalMsgID:6162865783958235 OK: 0; Sent queued message ID: 9589936487b8d0a1 SMSGlobalMsgID:6141138716371692
    STR;
    

    preg_split ,使用如下正则表达式:

    $lines = preg_split('/SMSGlobalMsgID: (\d+) /', $str);
    

    $lines ,它看起来很好——现在您应该能够遍历thoses行了。


    然后,从初始化 $output 数组为空:

    $output = array();
    


    现在您必须在初始输入的行上循环,在每行上使用一些regex魔术:
    请参阅的文档 preg_match Regular Expressions (Perl-Compatible) 更多信息

    foreach ($lines as $line) {
      if (preg_match('/^(\w+): (\d+); Sent queued message ID: ([a-z0-9]+) SMSGlobalMsgID:(\d+)$/', trim($line), $m)) {
        $output[] = array_slice($m, 1);
      }
    }
    

    注意我用 ()


    数组:

    var_dump($output);
    

    看起来是这样的:

    array
      0 => 
        array
          0 => string 'OK' (length=2)
          1 => string '0' (length=1)
          2 => string 'e3674786a1c5f7a1' (length=16)
          3 => string '6162865783958235' (length=16)
      1 => 
        array
          0 => string 'OK' (length=2)
          1 => string '0' (length=1)
          2 => string '9589936487b8d0a1' (length=16)
          3 => string '6141138716371692' (length=16)
    
    推荐文章