Search code examples
phpsplit

Split string before each 5-digit string followed by a keyword


I have a string like $str.

$str = "**00016**cam 3212543**00022**cam 3212543123153**00020**cam 32125433153";

I want to split it in array like this. The numbers before 'cam' is the string length.

$splitArray = ["00016cam 3212543", "00022cam 3212543123153", "00020cam 32125433153"]

I have tried following code:

$lengtharray = array(); 
while ($str != null) 
{ 
     $sublength = substr($str, $star, $end); 
     $star += (int)$sublength; // echo $star."<br>"; // echo $sublength."<br>"; 
     if($star == $total)
     { 
         exit; 
     }
     else
     { 

     } 

      array_push($lengtharray, $star); // echo 
      print_r($lengtharray); 
}

Solution

  • If your string doesn't contain stars then I'm afraid you need to write a simple parser that will:

    • take characters from the left until it's not numeric
    • do substr having the length
    • repeat previous steps on not consumed string

      <?php
      
      $input = "00016cam 321254300022cam 321254312315300020cam 32125433153";
      
      function parseArray(string $input)
      {
          $result = [];
      
          while ($parsed = parseItem($input)) {
              $input = $parsed['rest'];
              $result[] = $parsed['item'];
          }
      
          return $result;
      }
      
      function parseItem(string $input)
      {
          $sLen = strlen($input);
          $len = '';
          $pos = 0;
          while ($pos < $sLen && is_numeric($input[$pos])) {
              $len .= $input[$pos];
              $pos++;
          }
      
          if ((int) $len == 0) {
              return null;
          }
      
          return [
              'rest' => substr($input, $len),
              'item' => substr($input, 0, $len)
          ];
      }
      
      var_dump(parseArray($input));