php split string based on pattern

前端 未结 2 1671
甜味超标
甜味超标 2021-01-26 00:48

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,4         


        
相关标签:
2条回答
  • 2021-01-26 01:39

    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',
    )
    
    0 讨论(0)
  • 2021-01-26 01:41

    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.

    0 讨论(0)
提交回复
热议问题