将格式化字符串转换为数组的最快方法


Fastest way to convert a formatted string to an array?

将这个字符串转换为这个数组的最快方法是什么?

$string = 'a="b" c="d" e="f"';
Array (
a => b
c => d
e => f
)

假设它们总是用空格分隔,并且值总是用引号括起来,您可以explode()两次并去掉引号。可能有一种更快的方法,但是这种方法非常简单。

$string = 'a="b" c="d" e="f"';
// Output array
$ouput = array();
// Split the string on spaces...
$temp = explode(" ", $string);
// Iterate over each key="val" group
foreach ($temp as $t) {
  // Split it on the =
  $pair = explode("=", $t);
  // Append to the output array using the first component as key
  // and the second component (without quotes) as the value
  $output[$pair[0]] = str_replace('"', '', $pair[1]);
}
print_r($output);
array(3) {
  ["a"]=>
  string(1) "b"
  ["c"]=>
  string(1) "d"
  ["e"]=>
  string(1) "f"
}

json_decode接近您请求的内容。

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
<?php
$string = 'a="b" c="d" e="f"';
$string = str_replace('"','',$string);
$str1 = explode(' ',$string);
foreach($str1 as $val)
{
    $val2 = explode('=',$val);
    $arr[$val2[0]] = $val2[1];
}
print_r($arr);
?>

我建议使用正则表达式而不是脆弱的爆炸。这验证了结构,而不是期望最好的结果。它也很短:

preg_match_all('/('w+)="([^"]*)"/', $input, $match);
$map = array_combine($match[1], $match[2]);

看起来它是php脚本,你是指。但是请按照建议添加php标签。

我不确定是否有一种直接的方式来分割它,因为你希望索引是默认索引以外的东西。

解决这个问题的算法如下:

  1. 用空格分隔符
  2. 分隔
  3. 从每个生成的字符串中删除分号
  4. 使用'='拆分每个生成的字符串
  5. 用字符串before =作为键,after =作为值添加元素到新的数组

我不确定这是最快的。

我不保证它的速度或可靠性,因为运行准确的基准测试需要您的真实数据(质量和容量)。

无论如何,为了向读者展示另一种方法,我将使用parse_str()

代码(演示):

$string = 'a="b" c="d" e="f"';
parse_str(str_replace(['"',' '],['','&'],$string),$out);
var_export($out);

去掉双引号并用&号替换所有空格。

当一个值包含空格或双引号时,这个方法和本页上的其他方法一样,会混淆你的数据。

输出:

array (
  'a' => 'b',
  'c' => 'd',
  'e' => 'f',
)

郑重声明,马里奥的答案将是本页上最可靠的。