如何将字符串转换为仅包含双引号字符的数组

How to cast string into array with only characters in double quotes

我需要将 $string = ("one","two","three,subthree","four") 转换为 PHP 数组。

$data[0] => "one",
$data[1] => "two",
$data[2] => "three,subthree",
$data[3] => "four"

问题是第 3 个变量中的分隔符包含逗号,因此 explode 函数将字符串变成 5 个变量而不是 4 个。

您可以使用 substr 删除第一个 ("") 然后使用 explode:

$string = '("one","two","three,subthree","four")';
$s = substr($string,2,-2); 
// now $s is: one","two","three,subthree","four
print_r(explode('","', $s));

输出:

(
    [0] => one
    [1] => two
    [2] => three,subthree
    [3] => four
)

实例:3v4l

您可以将字符串转换为 JSON 字符串,然后像这样解码

$string = '("one","two","three,subthree","four")';
$string = str_replace(['(', ')'], ['[', ']'], $string);

$array = json_decode($string, true);
print_r($array);

工作demo


编辑:

如果您有可能在字符串中使用方括号 [( or )],您可以通过方括号 [( or )] trim 并通过定界符 "," 展开。示例:

$string = '("one","two","three,subthree","four")';
$string = trim($string, ' ()');

$array = explode('","', $string);
print_r($array);

另一种方法是通过模式 ~"([^"])+"~

使用 preg_match_all()
$string = '("one","two","three,subthree","four")';
preg_match_all('~"([^"]+)"~', $string, $array);
print_r($array[0]);

Regex 解释:

  • " 匹配双引号
  • ([^"]+) 捕获组
  • [^"] 除双引号外的任何字符
  • + 出现一次或多次
  • " 匹配双引号

这是一个较短的版本:

$string = '("one", "two,three")';

preg_match_all('/"([^"]+)"/', $string, $string);

echo "<pre>";
var_dump($string[1]);

输出:

array(2) {
 [0]=>
  string(3) "one"
 [1]=>
 string(9) "two,three"
}

您可以将 explodetrim

一起使用
$string = '("one","two","three,subthree","four")';
print_r(explode('","',trim($string,'"()')));

工作示例:https://3v4l.org/4ZERb

为您处理报价的一种简单方法是使用 str_getcsv()(删除开始和结束括号后)...

$string = '("one","two","three,subthree","four")';
$string = substr($string, 1, -1);
print_r(str_getcsv($string));

给予

Array
(
    [0] => one
    [1] => two
    [2] => three,subthree
    [3] => four
)

主要是它也适用于...

$string = '("one","two","three,subthree","four",5)';

并输出

Array
(
    [0] => one
    [1] => two
    [2] => three,subthree
    [3] => four
    [4] => 5
)