如何用逗号分隔字符串,而不用引号(«»)引起逗号?

时间:2018-09-04 08:27:38

标签: php regex

我需要用逗号分隔字符串,但不要用引号(«»)引起。

我有一个类似data <- data.frame( group = c("A", "B", "C"), variable_with_long_name_1 = c(0,1,0.5), variable_with_long_name_2 = c(0,1,.5), variable_with_long_name_3 = c(1,0,0.5) )

的字符串

我想要这个结果:

"5,test2,4631954,Y,«some, string, text.»,299.00 TJS,http://some-link"

尝试使用preg_split,str_getcsv,但未获得所需的结果。

[
 0 => 5,
 1 => test2,
 2 => 4631954,
 3 => Y,
 4 => «some, string, text.»,
 5 => 299.00 TJS,
 6 => http://some-link
]

2 个答案:

答案 0 :(得分:4)

如果在字符串分割中没有常规的引号,可以使用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 demo

模式详细信息

  • «[^«»]*»(*SKIP)(*F)-«,除了«»之外的0+个字符,然后匹配»,正则表达式引擎移到末尾匹配的文本,然后从当前的匹配缓冲区中删除整个文本,引擎继续搜索下一个匹配项
  • |-或
  • \s*,\s*-一个,包含0+空格

输出:

Array
(
    [0] => 5
    [1] => test2
    [2] => 4631954
    [3] => Y
    [4] => «some, string, text.»
    [5] => 299.00 TJS
    [6] => http://some-link
)

答案 1 :(得分:0)

$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);