在引号内的单词除外,将字符串按空格分割

5
我有一个字符串,类似于:
$string = 'Some of "this string is" in quotes';

我想要获取一个数组,其中包含通过执行操作可以获得的字符串中的所有单词。
$words = explode(' ', $string);

然而,我不想在引号中拆分单词,因此理想情况下,最终的数组将是什么。
array ('Some', 'of', '"this string is"', 'in', 'quotes');

有人知道我该怎么做吗?

4个回答

10

您可以使用:

$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 );

输出:

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

正则表达式分析

("[^"]*")    # 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

1
感谢您的解释,非常有帮助。 - Bender

2

与其这样做,你可以采用另一种方式即匹配。与其分割,匹配会更加容易。

因此,请使用正则表达式:/[^\s]+|".*?"/preg_match_all 结合使用。


1
你可以使用正则表达式进行匹配,而不是分割来获取值:
/"[^"]+"|\w+/g

这将匹配:

  • "[^"]+" - 引号 " 之间的字符,
  • \w+ - 一组单词字符(A-Za-z_0-9),

演示


0
我认为你可以使用这样的正则表达式:
/("[^"]*")|(\S+)/g

你可以使用替换 $2

[正则表达式演示]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接