我想以一种不同的方式爆炸变量

时间:2015-10-30 05:51:36

标签: php

我有这个变量。

$var = "A,B,C,D,'1,2,3,4,5,6',E,F";

我想爆炸它,以便我得到以下数组。

array(
[0] => A,
[1] => B,
[2] => C,
[3] => D,
[4] => 1,2,3,4,5,6,
[5] => E,
[6] => F
);

我使用explode(',',$var),但我没有得到我想要的输出。有什么建议吗?

5 个答案:

答案 0 :(得分:77)

现有的函数可以解析逗号分隔的字符串。该函数为str_getcsv

它的签名是这样的:

array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )

您唯一的更改是将第三个变量(机箱)更改为单引号而不是默认的双引号。

以下是一个示例。

$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
$array = str_getcsv($var,',',"'");

如果您var_dump数组,您将获得所需的格式:

array(7) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "C"
  [3]=>
  string(1) "D"
  [4]=>
  string(11) "1,2,3,4,5,6"
  [5]=>
  string(1) "E"
  [6]=>
  string(1) "F"
}

答案 1 :(得分:19)

只需使用preg_match_all以下正则表达式,如下所示

preg_match_all("/(?<=').*(?=')|\w+/",$var,$m);
print_r($m[0]);

正则表达式说明:

  • (?<=').*(?=')捕获'(quotes)
  • 中的每个角色
  • |\w+ |(OR)将获取除,
  • 以外的其余字符

Demo

Regex

答案 2 :(得分:6)

尽管preg_splitarray_map的效果非常好,但请参阅下面的示例explodetrim

$var = "A,B,C,D,'1,2,3,4,5,6',E,F";

$a = explode("'",$var);

//print_r($a);
/*
outputs
Array
(
    [0] => A,B,C,D,
    [1] => 1,2,3,4,5,6
    [2] => ,E,F
)
*/
$firstPart = explode(',',trim($a[0],',')); //take out the trailing comma
/*
print_r($firstPart);
outputs
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
)
*/
$secondPart = array($a[1]);

$thirdPart = explode(',',trim($a[2],',')); //tale out the leading comma
/*
print_r($thirdPart);
Array
(
    [0] => E
    [1] => F
)
*/

$fullArray = array_merge($firstPart,$secondPart,$thirdPart);
print_r($fullArray);
/*
ouputs
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => 1,2,3,4,5,6
    [5] => E
    [6] => F
)
*/

答案 3 :(得分:5)

您需要将字符串分解为数组。

但是,除了最后一个元素之外,你需要使用逗号。

以下是工作示例:

<?php
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
$arr = explode("'", $var);
$num = ! empty($arr[1]) ? str_replace(',', '_', $arr[1]) : '';
$nt = $arr[0] . $num . $arr[2]; 
$nt = explode(',', $nt);
$len = count($nt);
$na = array();
$cnt = 0;
foreach ($nt as $v) {
    $v = str_replace('_', ',', $v);
    $v .= ($cnt != $len - 1) ? ',' : '';
    $na[] = $v;
    ++$cnt; 
}

Demo

答案 4 :(得分:1)

$var = "A,B,C,D,'1,2,3,4,5,6',E,F";

$arr = preg_split("/(,)(?=(?:[^']|'[^']*')*$)/",$var);
foreach ($arr as $data) {
    $requiredData[] = str_replace("'","",$data);
}
echo '<pre>';
print_r($requiredData);

说明: 常规Exp。 : -

(?<=').*(?=') => Used to get all characters within single quotes(' '),

|\w+ |(OR) => Used to get rest of characters excepted comma(,) 

然后在foreach循环中,我正在替换单引号