使用preg_replace向数组添加引号

时间:2015-08-17 18:23:36

标签: php arrays regex preg-replace

我有这个数组:

$array = '[[Smarties, 50g, 3, 1.99], 
          [M&Ms Peanut, 49g, 3, 1.99], 
          [Oreo Cookies, 300g, 1, 3.99], 
          [Pepsi, 355ml, 3, 1.29]]';

我需要使用json_decode,所以我需要找到一种方法用这样的引号括住内部信息:

[["Smarties", "50g", "3", "1.99"], 
["M&Ms Peanut", "49g", "3", "1"."99"], 
["Oreo Cookies", "300g", "1", "3.99"], 
["Pepsi", "355ml", "3", "1.29"]]

我尝试使用preg_replace,这就是我目前所获得的(关闭,但它将价格分成两部分,并将双字名称分成两部分。):

[["Smarties", "50g", "3", "1"."99"], 
["M"&"Ms" "Peanut", "49g", "3", "1"."99"], 
["Oreo" "Cookies", "300g", "1", "3"."99"], 
["Pepsi", "355ml", "3", "1"."29"]]

我很难理解preg_replace,我希望有人可以提供帮助。

有没有办法使用分隔逗号作为指南来确定引号的放置位置?

3 个答案:

答案 0 :(得分:1)

对于一个有点粗糙,但具有上下文感知的正则表达式,可以使用:

$str = preg_replace("~ [\[\],\s]*\K [^,\[\]]+ ~x", '"$0"', $str);
                           ↑             ↑
                        skip ][,    capture non-
                        + space   commas/brackets

\K之前的charclass跳过结构字符,而第二个[…]只找到除逗号和括号之外的任何内容 - 然后用引号括起来。

答案 1 :(得分:0)

一个不是最佳的,但是有效的例子:

$result = json_decode(strtr(strtr($yourString, array('['=>'["', ']'=>'"]', ', '=>'","', ']","['=>'],[')), array(']","[' => '],[', '["[' => '[[', ']"]' => ']]')), true);

答案 2 :(得分:-1)

处理此字符串,例如

$sample = explode('],', $array);

foreach ($sample as &$v)
{
    $v = array_map('trim', explode(',', trim($v, '[ ]')));
}

现在,数组变为,

array (
  0 => 
  array (
    0 => 'Smarties',
    1 => '50g',
    2 => '3',
    3 => '1.99',
  ),
  1 => 
  array (
    0 => 'M&Ms Peanut',
    1 => '49g',
    2 => '3',
    3 => '1.99',
  ),
  2 => 
  array (
    0 => 'Oreo Cookies',
    1 => '300g',
    2 => '1',
    3 => '3.99',
  ),
  3 => 
  array (
    0 => 'Pepsi',
    1 => '355ml',
    2 => '3',
    3 => '1.29',
  ),
)

简单地说,json_encode()会给出,

string '[["Smarties","50g","3","1.99"],["M&Ms Peanut","49g","3","1.99"],["Oreo Cookies","300g","1","3.99"],["Pepsi","355ml","3","1.29"]]' (length=128)