2

I can't figure out how to explode white spaces in a string excluding what's inside quotes. I have found several regular expressions that can do the job, but the particularity here is that the quotes are preceded by an equal sign:

string = 'arg1="value1" arg2="value2" arg3="value3 value4 value5"';

I was able to isolate what's contained inside the quotes, but I can't get the complete pair arg1="value1 value2"

Thanks for your help.

Julien
  • 43
  • 4

2 Answers2

2
$test = 'arg1="value1" arg2="value2" arg3="value3 value4 value5"';
preg_match_all('#([a-zA-Z0-9]+)="([^"]+)"#', $test, $matches);
var_dump($matches);

Returns:

array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(13) "arg1="value1""
    [1]=>
    string(13) "arg2="value2""
    [2]=>
    string(27) "arg3="value3 value4 value5""
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "arg1"
    [1]=>
    string(4) "arg2"
    [2]=>
    string(4) "arg3"
  }
  [2]=>
  array(3) {
    [0]=>
    string(6) "value1"
    [1]=>
    string(6) "value2"
    [2]=>
    string(20) "value3 value4 value5"
  }
}

Sample here.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
0

Try This

<?php
$string = 'arg1="value1" arg2="value2" arg3="value3 value4 value5"';
$whitespacearray= explode(" ",$string);
print_r($whitespacearray);
?>
Manish Patel
  • 1,877
  • 1
  • 14
  • 15