0

Given the string abc "def ghi", how can I return the array:

[0] => abc
[1] => def ghi

Other examples:

abc "def ghi"   =>   ['abc','def ghi']
abc def         =>   ['abc','def']
Ryan
  • 14,682
  • 32
  • 106
  • 179
  • You even tagged it with `explode`, so where is the problem ? – Rizier123 Jul 08 '15 at 20:43
  • Explode doesn't work. But I found str_getcsv() which let's me accomplish the same, preserving quotes. – Ryan Jul 08 '15 at 20:45
  • Why doesn't `explode('"', $str);` not work for you ? – Rizier123 Jul 08 '15 at 20:47
  • Because I would also want `abc def` to return array ['abc','def'] – Ryan Jul 08 '15 at 20:48
  • duplicate of http://stackoverflow.com/questions/2202435/php-explode-the-string-but-treat-words-in-quotes-as-a-single-word – OIS Jul 08 '15 at 20:50
  • Good find @OIS. Interesting that the accepted answer uses preg_match_all(), but str_getcsv() seems easier. – Ryan Jul 08 '15 at 20:51
  • 1
    @Ryan the accepted answer is not always the best, correct or best suitted for your use case. :) But questions should not be duplicated anyway. - The question is just after PHP5.3 when str_getcsv() was introduced. – OIS Jul 08 '15 at 20:53

2 Answers2

2

str_getcsv()

$str = 'abc "def ghi"';
$arr = str_getcsv($str, ' ', '"');
print_r($arr);

Returns:

Array
(
    [0] => abc
    [1] => def ghi
)
Ryan
  • 14,682
  • 32
  • 106
  • 179
0

You can use:

$s = 'abc "def ghi"';
preg_match_all('/(?>"[^"]*"|\S+)/', $s, $m);

print_r($m[0]);
Array
(
    [0] => abc
    [1] => "def ghi"
)
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks. Is there an advantage of using preg_match_all() rather than str_getcsv()? – Ryan Jul 08 '15 at 20:47
  • It another alternative. To be honest I haven't performed any performance tests but my feeling is that `preg_match_all` might perform better. – anubhava Jul 08 '15 at 20:49