How to merge two delimiters in preg_split
? For example:
如何在preg_split中合并两个分隔符?例如:
$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.
实际上,当两个分隔符是邻居时,我想合并数组元素。换句话说,如果下一部分是第二个分隔符,则忽略第一个分隔符。
3 个解决方案
#1
3
Try using a character class: /[ ,]+/
尝试使用字符类:/ [,] + /
The +
is a quantifier meaning "1 or more"
+是量词意思是“1或更多”
#2
2
What about making sure that the situation doesn't happen in the first place :
如何确保首先不会发生这种情况:
<?php
$str = "this is a test , and more";
$str=preg_replace('/ *, */',',',$str);
$array = preg_split('/( |,)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($array);
?>
Array
(
[0] => this
[1] =>
[2] => is
[3] =>
[4] => a
[5] =>
[6] => test
[7] => ,
[8] => and
[9] =>
[10] => more
)
#1
3
Try using a character class: /[ ,]+/
尝试使用字符类:/ [,] + /
The +
is a quantifier meaning "1 or more"
+是量词意思是“1或更多”
#2
2
What about making sure that the situation doesn't happen in the first place :
如何确保首先不会发生这种情况:
<?php
$str = "this is a test , and more";
$str=preg_replace('/ *, */',',',$str);
$array = preg_split('/( |,)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($array);
?>
Array
(
[0] => this
[1] =>
[2] => is
[3] =>
[4] => a
[5] =>
[6] => test
[7] => ,
[8] => and
[9] =>
[10] => more
)