用于preg_match_all的php正则表达式

用于preg_match_all的php正则表达式,php,regex,preg-match-all,Php,Regex,Preg Match All,Hi im使用Preg_match_all函数遍历字符串并返回其值数组 $str = 'field1,field2,field3,field4,,,,,,,"some text, some other text",field6'; preg_match_all("~\"[^\"]++\"|[^,]++~", $str,$match); echo "<pre>"; print_r($match[0]); echo "<pre>"; 但是我也希望它能返回空白的帮助。 我

Hi im使用Preg_match_all函数遍历字符串并返回其值数组

$str = 'field1,field2,field3,field4,,,,,,,"some text, some other text",field6';

preg_match_all("~\"[^\"]++\"|[^,]++~", $str,$match);

echo "<pre>";
print_r($match[0]);
echo "<pre>";

<>但是我也希望它能返回空白的帮助。

我想你也会使用爆炸。

Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
    [10] => some text, some other text
    [11] => field6
)
小心:一些文本,一些其他文本将在数组的2个单元格中分开。

编辑:从explode更改为str_getcsv,以解决存储模块问题

我会用这个。它比preg_match_all更容易阅读和理解,而且它将完全按照您的要求执行,甚至返回空字符串

例如:


使用~[^]*.[^,]*,| ~实际上可以满足您的需要,但它的结尾总是有一个空字符串,因为这也是一个空字符串,它会将两个组添加到matches数组中。

可能有用吗?我已经尝试过使用它,但它不能满足我的需要。通过这种方式,我可以准确地编辑每个字段。你知道我怎么做吗?我不知道你的意思。str_getcsv将解析一个CSV格式的字符串,并为您提供一个值数组;它还将适当处理引用的文本。然后,您可以根据需要编辑生成的数组。这将返回与上面相同的结果。我刚刚从user729928运行了示例代码,它在返回的数组中包含了空字段。数组不包含双引号是不是有问题?天哪,上次我这样做时,我从未得到过该输出,我一定是在某些地方输入了错别字。。谢谢你…不,只要它分开就好。。。出于某种原因,这对我现在起作用了。
my_array = explode (',', $str);
<?php
$str = 'field1,field2,field3,field4,,,,,,,"some text, some other text",field6';

$results = str_getcsv($str);
print_r($results);
Array
(
    [0] => field1
    [1] => field2
    [2] => field3
    [3] => field4
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
    [10] => some text, some other text
    [11] => field6
)