Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 559
Alexander Teitelboym Avatar asked Sep 13 '12 10:09

Alexander Teitelboym


People also ask

How do you trim a string to a specific length in Python?

You can trim a string in Python using three built-in functions: strip() , lstrip(), rstrip() methods respectively. Python string. strip() method removes the white-spaces from the front and back end of a particular string.


1 Answers

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;
}
like image 160
noj Avatar answered Sep 29 '22 03:09

noj