Search code examples
phpstringunicodesplitfixed

Splitting string by fixed length


I am looking for ways to split a string of a unicode alpha-numeric type to fixed lenghts. for example:


    992000199821376John Smith          20070603

and the array should look like this:

Array (
 [0] => 99,
 [1] => 2,
 [2] => 00019982,
 [3] => 1376,
 [4] => "John Smith",
 [5] => 20070603
) 

array data will be split like this:

    Array[0] - Account type - must be 2 characters long,
    Array[1] - Account status - must be 1 character long,
    Array[2] - Account ID - must be 8 characters long,
    Array[3] - Account settings - must be 4 characters long,
    Array[4] - User Name - must be 20 characters long,
    Array[5] - Join Date - must be 8 characters long.

Solution

  • Or if you want to avoid preg:

    $string = '992000199821376John Smith          20070603';
    $intervals = array(2, 1, 8, 4, 20, 8);
    
    $start = 0;
    $parts = array();
    
    foreach ($intervals as $i)
    {
       $parts[] = mb_substr($string, $start, $i);
    
       $start += $i;
    }