2010-02-17 41 views
2

我从服务器得到这样的响应:PHP转化的特定字符串到数组值

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

等等...

这仅仅是一个长字符串没有回车我复制它到底收到。 请注意,初始OK可以是一个不同的单词以及0(在字符串的开头)可以是最多3位数的数字。

这是会重演的格局:

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

考虑您有数据作为一个字符串作为输入:

$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); 

编辑后的评论和编辑的OP

考虑到你收到的数据只在一行上,你必须找到另一种方法来分割它(我认为它更容易分割数据并处理一次处理大块数据的“线路” )

考虑您收到这样长相的数据:

$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的内容,它看起来相当不错 - 现在您应该可以遍历这些线。


然后,你开始通过初始化$output数组作为空单:

$output = array(); 


你现在必须遍历所有的初始输入线,采用每个一些正则表达式魔术行:
preg_matchRegular 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); 
    } 
} 

注的部分我拍摄的,使用()


而且,最终,你得到的$output阵列:

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) 
+0

谢谢你为了答案,但正如我所说的那样,没有人愿意回来,所以\ n不会工作。 +初始OK可以是不同的值以及0可以是最多3位数字。对不起,我没有说明,我更新了文章 – ondrobaco 2010-02-17 12:11:19

+0

哦:(-(我只是从你的问题中复制粘贴了字符串,它在两行上,在你编辑之前^^ ;;我会尝试一些想法,并且编辑我的答案,如果我找到一些有用的东西:-) *(编辑我的评论:我刚刚编辑我的答案,以提供一些额外的信息 - 现在应与非多行输入)* – 2010-02-17 12:17:04

+0

*“初始确定可以是一个不同的值,以及0可以高达3位数字“*”我的代码应该为此工作,因为我匹配'\ d +',这意味着*“至少一个数字”*。 – 2010-02-17 12:22:42