preg_split - 按白色 space 和所选字符拆分,但将字符保留在数组中

preg_split - split by white space and by chosen character but keep the character in array

所以我有这个问题,我想用包含白色 space( ) 和逗号 (,) 的模式拆分字符串。我设法按该模式拆分了我的字符串,但问题是我想将该逗号保留在数组中。这是我的字符串:

$string = "It's just me, myself, i and an empty glass of wine. Age = 21";

我是这样拆分的:

$split = preg_split('/[\s,]+/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

这是我在这个例子中得到的数组(你可以看到逗号消失了)

这是我现在拥有的:

Array
(
    [0] => It's
    [1] => just
    [2] => me
    [3] => myself
    [4] => i
    [5] => and
    [6] => an
    [7] => empty
    [8] => glass
    [9] => of
    [10] => wine.
    [11] => Age
    [12] => =
    [13] => 21
)

这是我想要的:

Array
(
    [0] => It's
    [1] => just
    [2] => me
    [3] => ,
    [4] => myself
    [5] => ,
    [6] => i
    [7] => and
    [8] => an
    [9] => empty
    [10] => glass
    [11] => of
    [12] => wine.
    [13] => Age
    [14] => =
    [15] => 21
)

如果那个逗号前有一个 space 并且那个逗号不在那个模式中,我将它放入由 preg_split 生成的数组中,但问题是我希望它得到那个逗号前面有或没有 space。

有办法实现吗?

谢谢! :D

the problem is that i want to keep that comma in array

那么只要使用标志PREG_SPLIT_DELIM_CAPTURE

PREG_SPLIT_DELIM_CAPTURE

If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

http://php.net/manual/en/function.preg-split.php

所以你会这样拆分

$split = preg_split('/(,)\s|\s/', $string, null, PREG_SPLIT_DELIM_CAPTURE);

你可以在这里测试

https://3v4l.org/Eq8uS

对于 Limit 参数,null-1 更合适,因为我们只想跳到标志参数。当你阅读它时它会更干净,因为 null 在 -1 可能有一些重要价值的地方没有任何意义(在这种情况下它没有)但它只是让不知道 preg_split 的人更清楚好吧,我们只是忽略了那个论点。

您打算在每个 space 或逗号前的零宽度位置拆分字符串。

以下模式将在(和 absorb/destroy)spaces 以及逗号前瞻中展开 - 在这种情况下,不会丢失该限定分隔符的字符。

在编写此模式时,您不需要包含 preg_split().

可用的第 3 个或第 4 个参数

对于最严格的做法,当您的输入可能格式不正确时,您可能需要包含 NO_EMPTY 标志(实现为 preg_split('/ |(?=,)/', $string, 0, PREG_SPLIT_NO_EMPTY)

代码:(Demo)

$string = "It's just me, myself, i and an empty glass of wine. Age = 21";

$array = preg_split('/ |(?=,)/', $string);

print_r($array);

输出:

Array
(
    [0] => It's
    [1] => just
    [2] => me
    [3] => ,
    [4] => myself
    [5] => ,
    [6] => i
    [7] => and
    [8] => an
    [9] => empty
    [10] => glass
    [11] => of
    [12] => wine.
    [13] => Age
    [14] => =
    [15] => 21
)