So i have this problem, i want to split a string by a pattern that contains white space( ) and comma (,). I managed to split my string by that pattern but the problem is that i want to keep that comma in array. Here is my string:
$string = "It's just me, myself, i and an empty glass of wine. Age = 21";
Here is how i split it:
$split = preg_split('/[s,]+/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Here is the array that i’m getting in this example(as you can see that comma disappears)
This is the one that i have now:
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 )
This is the one that i want:
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 )
If there is a space before that comma and that comma is not in that pattern i get it into that array that’s generated by preg_split but the problem is that i want it to get that comma with or without space before it.
Is there a way to achieve this?
Thank you! 😀
Advertisement
Answer
the problem is that i want to keep that comma in array
Then just use the flag 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
So you will split it like this
$split = preg_split('/(,)s|s/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
You can test it here
For the Limit argument null
is more appropriate then -1
because we just want to skip to the flag argument. It’s more clean when you read it because null means nothing where -1
may have some important value (in this case it doesn’t) but it just makes it clearer for someone that doesn’t know preg_split
as well that we are just ignoring that argument.