-1

How would one split a string in php by spaces that are not enclosed within double quotes? For example, this:

"hello my \"name is bob\""

Would become this:

["hello", "my", "\"name is bob\""]
mntruell
  • 181
  • 1
  • 13

3 Answers3

2

You can use this pettern: /\s(?=([^"]*"[^"]*")*[^"]*$)/ String can be long as you want, quotes may be escaped or unescaped. This: "hello my \"name is bob\" hello my \"name is john\" end" or this 'hello my "name is bob" hello my "name is john" end' is possible.

Example of usage:

$array = preg_split('/\s(?=([^"]*"[^"]*")*[^"]*$)/', "hello my \"name is bob\" hello my \"name is john\" end");
Jan Rydrych
  • 2,188
  • 2
  • 13
  • 18
1

You could use this function based on a regular expression:

function splitNonQuoted($data) {
    preg_match_all('/\S*?(".*?"\S*?)*( |$)/', $data, $matches);
    array_pop($matches[0]);
    return $matches[0];
}

Example use:

print_r (splitNonQuoted("hello my \"name is bob\""));

Output:

Array
(
    [0] => hello 
    [1] => my 
    [2] => "name is bob"
)
trincot
  • 317,000
  • 35
  • 244
  • 286
1

Here is solution with preg_split just for your particular case:

$words = preg_split('/(?!\\"\w+?)\s+(?!\w+\s*?\w*\\"\Z)/', "hello my \"name is bob\"");
var_dump($words);

// output:
array(3) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(2) "my"
  [2]=>
  string(13) ""name is bob""
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105