preg_split - 由空格和所选字符分割,但将字符保留在数组中

时间:2018-04-16 18:33:56

标签: php regex preg-split

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

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

如果在该逗号之前有一个空格并且该逗号不在该模式中,则将其放入由preg_split生成的数组中,但问题是我希望它在之前有或没有空格的逗号。

有没有办法实现这个目标?

谢谢! :d

2 个答案:

答案 0 :(得分:1)

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

然后只使用标志PREG_SPLIT_DELIM_CAPTURE

  

<强> PREG_SPLIT_DELIM_CAPTURE

     

如果设置了此标志,则将捕获并返回分隔符模式中的带括号的表达式。

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更合适,因为我们只想跳转到flag参数。当你阅读它时它更干净,因为null意味着-1可能有一些重要的值(在这种情况下它没有),但它只是让那些不知道preg_split的人更清楚好吧,我们只是忽略了那个论点。

答案 1 :(得分:0)

您打算在逗号前在每个空格或零宽度位置分割字符串。

以下模式将在(并吸收/破坏)空格上爆炸,并提前显示逗号-在这种情况下,该限定符不会丢失任何字符。

在编写此模式时,您将不需要包括preg_split()可用的第3或第4参数。

对于最严格的做法,当您的输入可能格式不正确时,您可能需要包括NO_EMPTY标志(实现为preg_split('/ |(?=,)/', $string, null, 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
)