问题
以英文逗号作为分隔符,使用explode把字符串切割为数组
为了不影响分割,当值含有英文逗号时,需要在两侧加双引号(如:"a,b"),且值不能包含双引号
需要实现:分割后保持双引号中内容的完整性
解决方案
/*
字符串:
$text = "小张,13006701576,\"123@163.com\",1,\"繁體字,测试,测试222\",test,user";
预期得到数组:
$arr = array(
"小张",
"13006701576",
"123@163.com",
"1",
"繁體字,测试,测试222",
"test",
"user"
);
*/
/*
1、使用表达式|\"(.*?)\"|匹配字符串中使用括号括起来的内容
2、使用表达式/,/把双引号内容的英文逗号替换为%comma%,再以英文逗号使用explode分割
3、分割完成后,循环数组,使用str_replace把内容中的%comma%替换回英文逗号
*/
$text = "小张,13006701576,\"123@163.com\",1\"繁體,字,测试,测试222\",test,user";
$string = preg_replace_callback(
"|\"(.*?)\"|",
function ($matches) {
return preg_replace("/,/", "%comma%", $matches[1]);
},
$text);
$arr = explode(",", $string);
foreach ($arr as &$item){
$item = str_replace("%comma%", ",", $item);
}
echo json_encode($arr);