[英]Regular Expression to Split this string
I want to split following string with a comma. 我想用逗号分割后面的字符串。
1,"x1",43,"tr","y,7"
Result array should be like following. 结果数组应如下所示。
0=>1
1=>"x1"
2=>43
3=>"tr"
4=>"y,7"
In short, it should not consider comma if it is between quotes. 简而言之,如果在引号之间,则不应考虑逗号。
If I use explode, I will get following result, which I don't want. 如果使用explode,我会得到以下结果,这是我不想要的。
[4:58:20 PM] Mihir Dhandha: 0=>1
1=>"x1"
2=>43
3=>"tr"
4=>"y
5=>7"
I am stuck here, please help. 我被困在这里,请帮忙。
Try str_getcsv
: 试试
str_getcsv
:
<?php
$s = '1,"x1",43,"tr","y,7"';
$result = str_getcsv($s);
var_dump($result);
echo "\n";
// array(5) {
// [0]=>
// string(1) "1"
// [1]=>
// string(2) "x1"
// [2]=>
// string(2) "43"
// [3]=>
// string(2) "tr"
// [4]=>
// string(3) "y,7"
// }
?>
The following snippet: 以下代码段:
$s = '1,"x1",43,"tr","y,7"';
print_r(preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $s));
produces: 产生:
Array
(
[0] => 1
[1] => "x1"
[2] => 43
[3] => "tr"
[4] => "y,7"
)
as can be seen on ideone . 从ideone上可以看出。
The regex ,(?=([^"]*"[^"]*")*[^"]*$)
means: match a comma, only if it has zero, or an even number of double quotes ahead of it. 正则表达式
,(?=([^"]*"[^"]*")*[^"]*$)
意思是:仅当逗号为零或双引号为偶数时,才匹配逗号。
Easy!! 简单!! Your string is a CSV.
您的字符串是CSV。
Use $your_array=str_getcsv($your_string);
使用
$your_array=str_getcsv($your_string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.