从字符串构建数组

时间:2012-03-06 20:35:10

标签: php

我从服务中检索了以下输出。

输出:

  

确定:设置用户名确定:设置密码确定:设置服务器状态获取 - 网络确定:登录确定:get-group-members组联系人列表联系人5551000008539名称“驱动程序2”状态脱机组联系人列表联系人5551000008540名称“驱动程序3”状态脱机组联系人列表联系人5551000008541名称“驱动程序4”状态脱机状态连接client-own-id 5551000008535 client-own-id 0 client-own-id 5551000008535状态断开登录拒绝auth-error客户端-own-id 0状态离线

如何像以前一样将数据提取到用户数组中?

我怎么能爆炸/内爆/ preg匹配或任何用户数组。像:

$users - Driver 2 => 5551000008539
         Driver 3 => 5551000008540
         Driver 4 => 5551000008541

2 个答案:

答案 0 :(得分:1)

<?php
$str = 'OK: set username OK: set password OK: set server state acquiring-network OK: sign-in OK: get-group-members group contact-list contact 5551000008539 name "Driver 2" state offline group contact-list contact 5551000008540 name "Driver 3" state offline group contact-list contact 5551000008541 name "Driver 4" state offline state connecting client-own-id 5551000008535 client-own-id 0 client-own-id 5551000008535 state disconnecting sign-in denied auth-error client-own-id 0 state offline';
preg_match_all('@contact (\d+) name "(.+?)"@', $str, $matches, PREG_SET_ORDER);
print_r($matches);
$array = array();
foreach($matches as $match) {
    $array[$match[2]] = $match[1];
}
print_r($array);

从$ match中抢救数据留作练习。

答案 1 :(得分:0)

试试这个(假设$s包含我们服务的输出):

preg_match_all("/contact-list contact (\\d+) name \"(.*?)\"/", $s, $out, PREG_PATTERN_ORDER);

创建一个名称为键,数字为值的数组:

$result = array_combine($out[2], $out[1]);