arrays - php split string based on pattern


Keywords:php 


Question: 

I have a string like this:

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

As you see there are semicolons between values. I want to split this string based on 'only semicolons before 7 digits values' so I shoud have this.

>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

the only thing that I can think of is explode(';',$string) but this returns this:

>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

Is there any fast method to split string with this format based on the ";" before 7 digits values??


2 Answers: 

You can use preg_split for that:

$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));

Your output will be

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"
}

I think that the next thing (combine the 1st and 2nd and then 3rd and 4th elements) is not a big deal :)

Let me know if you still here problems here.

 

You could do a find and replace on numbers that are seven digits long, to insert a token that you can use to split. The output may need a little extra filtering to get to your desired format.

<?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);

Output:

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',
)