![](/img/trans.png)
[英]PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
[英]How can I explode a string by commas, but not where the commas are within this («») quotes?
我需要用逗号分隔字符串,但不能用引号(«»)来分解。
我有一个字符串,如: "5,test2,4631954,Y,«some, string, text.»,299.00 TJS,http://some-link"
我想要这个结果:
[
0 => 5,
1 => test2,
2 => 4631954,
3 => Y,
4 => «some, string, text.»,
5 => 299.00 TJS,
6 => http://some-link
]
尝试使用preg_split,str_getcsv,但没有得到所需的结果。
$res = str_getcsv($res, ',');
$res = preg_split("/(?<=\)),/", $res);
如果您没有常规引号来处理字符串中的分割,您可以使用基于SKIP-FAIL based
正则表达式获得所需的内容:
$s = "5,test2,4631954,Y,«some, string, text.»,299.00 TJS,http://some-link";
print_r(preg_split('~«[^«»]*»(*SKIP)(*F)|\s*,\s*~', $s));
请参阅PHP演示
图案细节
«[^«»]*»(*SKIP)(*F)
- «
,除了«
和»
之外的0 +字符,然后»
匹配,正则表达式引擎移动到此匹配文本的末尾,然后从当前匹配缓冲区中删除整个文本,引擎继续搜索下一个匹配项 |
- 要么 \\s*,\\s*
- a ,
用0+空格括起来 输出:
Array
(
[0] => 5
[1] => test2
[2] => 4631954
[3] => Y
[4] => «some, string, text.»
[5] => 299.00 TJS
[6] => http://some-link
)
$theString = "5,test2,4631954,Y,«some, string, text.»,299.00 TJS,http://some-link";
$var_arr = array();
$j = mb_strlen($theString);
$chars = "";
for ($k = 0; $k < $j; $k++)
{
$char = mb_substr($theString, $k, 1);
if($char == "," )
{
if (!\preg_match("/[\«»]/", $chars)) {
$var_arr[] = $chars.",";
$chars = "";
}
else{
if(preg_match("/«(.*?)»/",$chars))
{
$var_arr[] = $chars.",";
$chars = "";
}
else
$chars .= $char;
}
}
else{
$chars .= $char;
}
if( ($k + 1) == $j)
{
$var_arr[] = $chars;
}
}
print_r($var_arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.