I need to split string by spaces, but phrase in quotes should be preserved unsplitted. Example:
word1 word2 \"this is a phrase\" word3 word4 \"this is a s
Anybody want to benchmark tokenizing vs. regex? My guess is the explode() function is a little too hefty for any speed benefit. Nonetheless, here's another method:
(edited because I forgot the else case for storing the quoted string)
$str = 'word1 word2 "this is a phrase" word3 word4 "this is a second phrase" word5';
// initialize storage array
$arr = array();
// initialize count
$count = 0;
// split on quote
$tok = strtok($str, '"');
while ($tok !== false) {
// even operations not in quotes
$arr = ($count % 2 == 0) ?
array_merge($arr, explode(' ', trim($tok))) :
array_merge($arr, array(trim($tok)));
$tok = strtok('"');
++$count;
}
// output results
var_dump($arr);