在除引号中的单词之外的空格上拆分字符串

Ben*_*der 3 php regex string

我有一个字符串

$string = 'Some of "this string is" in quotes';
Run Code Online (Sandbox Code Playgroud)

我想得到一个字符串中所有单词的数组,我可以通过这样做

$words = explode(' ', $string);
Run Code Online (Sandbox Code Playgroud)

但是我不想将引号中的单词拆分,所以理想情况下是结束数组

array ('Some', 'of', '"this string is"', 'in', 'quotes');
Run Code Online (Sandbox Code Playgroud)

有谁知道我怎么做到这一点?

anu*_*ava 8

您可以使用:

$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 );
Run Code Online (Sandbox Code Playgroud)

输出:

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

RegEx分手

("[^"]*")    # 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
Run Code Online (Sandbox Code Playgroud)