1

我有字符串,就像abc xyz "a x" test "test1 test2"我想用空格分割字符串一样,但引号内的单词应该保持原样。我可以使用explode 拆分字符串,但explode 不能按照我的要求在这里工作。

爆炸/拆分输出后应该像

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

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

4

2 回答 2

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."
}

取自这里:发布

于 2013-04-04T11:41:20.097 回答
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
于 2013-04-04T11:58:17.917 回答