I have this simple pattern that splits a text into periods
$text = preg_split("/[\.:!\?]+/", $text);
but i want to include . : or ! at the end of array items
IE now for "good:news.everyone!" i have:
array("good","news","everyone","");
but what i want is:
array("good:","news.","everyone!","");
Here you go:
How it works: The pattern actually turns everything into a delimiter. Then, to include these delimiters in the array, you can use the
PREG_SPLIT_DELIM_CAPTURE
constant. This will return an array like:To get rid of the empty values, use
PREG_SPLIT_NO_EMPTY
. To combine two or more of these constants, we use the bitwise|
operator. The result:No use for
PREG_SPLIT_DELIM_CAPTURE
if you use a positive lookbehind in your pattern. The function will keep the delimiters.If you use
lookbehind
, it will just look for the character without matching it. So, in the case ofpreg_split()
, the function will not discard the character.The result without
PREG_SPLIT_NO_EMPTY
flag:The result with
PREG_SPLIT_NO_EMPTY
flag:You can test it using this PHP Online Function Tester.