0

I need to generate an array with preg_split, as implode('', $array) can re-generate the original string. `preg_split of

$str = 'this is a test "some quotations is her" and more';
$array = preg_split('/( |".*?")/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

generates an array of

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] => 
    [8] => 
    [9] => "some quotations is here" 
    [10] => 
    [11] => 
    [12] => and
    [13] =>  
    [14] => more
)

I need to take care of the space before/after the quotation marks too, to generate an array with the exact pattern of the original string.

For example, if the string is test "some quotations is here"and, the array should be

Array
(
        [0] => test
        [1] => 
        [2] => "some quotations is here" 
        [3] => and
)

Note: The edit has been made based on initial discussion with @mikel.

Googlebot
  • 15,159
  • 44
  • 133
  • 229

2 Answers2

2

Will this work for you ?

preg_split('/( ?".*?" ?| )/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
Michael Low
  • 24,276
  • 16
  • 82
  • 119
  • sorry, I have a small problem with this solution. It will add double space (the first delimiter) before and after the quotation mark. In fact, it will action with both delimiters at the same time. – Googlebot Dec 22 '12 at 08:54
  • Thanks for the edit, but now it will remove all spaces. Of course, it was poorly presented in my question too. In any case, I need to have an array of exact pattern of the string. If there is a space before/after the quotation or no space; I need to have them in the generated array. – Googlebot Dec 22 '12 at 09:03
1

This should do the trick

$str = 'this is a test "some quotations is her" and more';
$result = preg_split('/(?:("[^"]+")|\b)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$result = array_slice($result, 1,-1);

Output

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] =>  
    [8] => "some quotations is her"
    [9] =>  
    [10] => and
    [11] =>  
    [12] => more
)

Reconstruction

implode('', $result);
// => this is a test "some quotations is her" and more
maček
  • 76,434
  • 37
  • 167
  • 198
  • Thanks, as I edited, I need to have the space (first delimiter) in the array. It may be present or absent before/after the quotation mark. – Googlebot Dec 22 '12 at 09:10
  • Thanks for the edit, but `implode('', $array)` will not generate the original string if there is no space after quotation marks; e.g. `her"and`. This will work for space/no space before the quotation mark, but not after. – Googlebot Dec 22 '12 at 10:09
  • All, it certainly does reconstruct the original string. You can even see the spaces (empty values) in the array after `her"`. – maček Dec 22 '12 at 23:33