[SOLVED] Split string on semicolons immediately followed by 7 digital characters

Issue

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 should 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?

Solution

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.

Answered By – Dekel

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *