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\""]
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\""]
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");
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"
)
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""
}