我有一个这样的字符串:
2234323,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433;4534453,23,23,44,433;
3,23,44,433;23,23,44,433;23,23,44,433
7545455,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433
如您所见,值之间有分号。我想基于“7位数值之前的分号”分割此字符串'所以我应该有这个。
>2234323,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433
>4534453,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433;
>7545455,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433
我唯一能想到的是explode(';',$string)
,但这会返回:
>2234323,23,23,44,433;
>3,23,44,433;
>23,23,44,433;
>23,23,44,433
>4534453,23,23,44,433;
>3,23,44,433;
>23,23,44,433;23,23,44,433;
>7545455,23,23,44,433;
>3,23,44,433;23,23,44,433;
>23,23,44,433
是否有任何快速方法可以根据&#34 ;;"以此格式拆分字符串?之前的7位数值
答案 0 :(得分:1)
您可以使用preg_split
:
$s = '2234323,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433;4534453,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433;7545455,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433';
var_dump(preg_split('/(;\d{7},)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE));
您的输出将是
array(5) {
[0] =>
string(58) "2234323,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433"
[1] =>
string(9) ";4534453,"
[2] =>
string(50) "23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433"
[3] =>
string(9) ";7545455,"
[4] =>
string(50) "23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433"
}
我认为下一件事(结合第1和第2,然后是第3和第4个元素)并不是什么大事:))
如果你这里仍有问题,请告诉我。
答案 1 :(得分:1)
您可以对七位数的数字进行查找和替换,以插入可用于拆分的令牌。输出可能需要一些额外的过滤才能达到您想要的格式。
<?php
$in =<<<IN
2234323,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433;4534453,23,23,44,433;
3,23,44,433;23,23,44,433;23,23,44,433
7545455,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433
IN;
$out = preg_replace('/([0-9]{7})/', "@$1", $in);
$out = explode('@', $out);
$out = array_filter($out);
var_export($out);
输出:
array (
1 => '2234323,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433;',
2 => '4534453,23,23,44,433;
3,23,44,433;23,23,44,433;23,23,44,433
',
3 => '7545455,23,23,44,433;3,23,44,433;23,23,44,433;23,23,44,433',
)