按空格将字符串转换为数组

时间:2015-11-07 07:29:41

标签: php arrays

我有以下示例字符串

device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274

我想将此字符串转换为数组

预期输出

device_name="Text Data"
d_id=7454579598
status="Active" 
Key=947-4378-43248274

我尝试使用爆炸功能,但它提供了以下输出

$data='device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274';
$arr= explode("",$data);

生成输出

device_name="Text 
Data"
d_id=7454579598
status="Active" 
Key=947-4378-43248274

3 个答案:

答案 0 :(得分:0)

试试这段代码

    $str = 'device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274';
$pattern = '/(\\w+)\s*=\\s*("[^"]*"|\'[^\']*\'|[^"\'\\s>]*)/';
preg_match_all($pattern, $str, $matches, PREG_SET_ORDER);

$attrs = array();
foreach ($matches as $match) {
    if (($match[2][0] == '"' || $match[2][0] == "'") && $match[2][0] == $match[2][strlen($match[2])-1]) {
        $match[2] = substr($match[2], 1, -1);
    }
    $name = strtolower($match[1]);
    $value = html_entity_decode($match[2]);
    $attrs[$name] = $value;
}
print_r($attrs);

输出

Array ( [device_name] => Text Data [d_id] => 7454579598 [status] => Active [key] => 947-4378-43248274 ) 

答案 1 :(得分:0)

使用正则表达式考虑这个小而简单的例子:

<?php    
$subject = 'device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274';
$pattern = '/^device_name="(.*)" d_id=(\d+) status="(.*)" Key=([0-9-]*)$/';
preg_match($pattern, $subject, $tokens);
var_dump($tokens);

这会创建此输出:

array(5) {
  [0] =>
  string(77) "device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274"
  [1] =>
  string(9) "Text Data"
  [2] =>
  string(10) "7454579598"
  [3] =>
  string(6) "Active"
  [4] =>
  string(17) "947-4378-43248274"
}

从这里你可能会继续自己: - )

答案 2 :(得分:0)

首先转换为JSON。 JSON Docs

$str = 'device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274';
$json = '{'.str_replace('=',':',$str).'}';
$json = '{'.str_replace(' ',',',$str).'}';

获取JSON。像:

{device_name:"Text Data",d_id:7454579598,status:"Active",Key:947-4378-43248274}

并转换为数组

$array = json_decode($json, true);

和输出

array(4) {
    ["device_name"] => "Text Data"
    ["d_id"] => 7454579598
    ["status"] => "Active"
    ["Key"] => "947-4378-43248274"
}