Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on spaces except words in quotes

Tags:

string

regex

php

I have a string like

$string = 'Some of "this string is" in quotes';

I want to get an array of all the words in the string which I can get by doing

$words = explode(' ', $string);

However I don't want to split up the words in quotes so ideally the end array will be

array ('Some', 'of', '"this string is"', 'in', 'quotes');

Does anyone know how I can do this?

like image 974
Bender Avatar asked Dec 10 '22 21:12

Bender


1 Answers

You can use:

$string = 'Some of "this string is" in quotes';
$arr = preg_split('/("[^"]*")|\h+/', $string, -1, 
                   PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r ( $arr );

Output:

Array
(
    [0] => Some
    [1] => of
    [2] => "this string is"
    [3] => in
    [4] => quotes
)

RegEx Breakup

("[^"]*")    # match quoted text and group it so that it can be used in output using
             # PREG_SPLIT_DELIM_CAPTURE option
|            # regex alteration
\h+          # match 1 or more horizontal whitespace
like image 101
anubhava Avatar answered Dec 21 '22 12:12

anubhava