爆炸的字符串,没有引号

时间:2013-04-04 11:34:02

标签: php

我有像abc xyz "a x" test "test1 test2"这样的字符串我想用空格分割字符串但是引号内的字应保持不变。我可以使用explode拆分字符串,但爆炸根据我的要求在这里不起作用。

爆炸/分裂输出后应该

[0] => abc
[1] => xyz
[2] => "a x"
[3] => test
[4] => "test1 test2"

我认为preg_split对我有用,但不知道正确的正则表达式。

2 个答案:

答案 0 :(得分:0)

这样做:

$str = 'this is a string  "that has quoted text" inside.';

// #1 version
$arOne = preg_split('#\s*("[^"]*")\s*|\s+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

// #2 version
$arTwo = preg_split('#\s*((?<!\\\\)"[^"]*")\s*|\s+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

<强>输出

array(6) {
  [0]=>
  string(4) "this"
  [1]=>
  string(2) "is"
  [2]=>
  string(1) "a"
  [3]=>
  string(6) "string"
  [4]=>
  string(22) ""that has quoted text""
  [5]=>
  string(7) "inside."
}

从这里采取:Post

答案 1 :(得分:0)

另一个好的和简单的答案是

$str = abc xyz "a x" test "test1 test2"
str_getcsv($str,' ','"');

将返回一个数组,以获取有关str_getcsv的更多详细信息 这将返回按空格分割的数组,而不是“

上面的输出

[0] => abc
[1] => xyz
[2] => a x
[3] => test
[4] => test1 test2