除引号中的单词外,在空格上拆分字符串 [英] Split string on spaces except words in quotes

查看:33
本文介绍了除引号中的单词外,在空格上拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的字符串

$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?

推荐答案

您可以使用:

$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

这篇关于除引号中的单词外,在空格上拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆