How to merge two delimiters in preg_split
? For example:
$str = "this is a test , and more";
$array = preg_split('/( |,)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($array);
will produce an array as
Array
(
[0] => this
[1] =>
[2] => is
[3] =>
[4] => a
[5] =>
[6] => test
[7] =>
[8] =>
[9] => ,
[10] =>
[11] =>
[12] => and
[13] =>
[14] => more
)
but I want to get
Array
(
[0] => this
[1] =>
[2] => is
[3] =>
[4] => a
[5] =>
[6] => test
[7] => ,
[8] => and
[9] =>
[10] => more
)
In fact, I want to merge the array elements when two delimiters are neighbors. In other words, ignoring the first delimiter if the next part is the second delimiter.
How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.
Try using a character class: /[ ,]+/
The +
is a quantifier meaning "1 or more"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With