Split php string into pieces of different lengths

I am looking for ways to split a string into an array, sort of str_split()where there are pieces of all different sizes.

I could do this by going through the line with the bundle substr(), but it does not look elegant and inefficient. Is there a function that takes a string and an array, like ( 1, 18, 32, 41, 108, 125, 137, 152, 161), and outputs an array of correctly sliced ​​strings?

Explode is not suitable because the pieces are separated by changing the number of spaces.

+5
source share
3 answers

There is nothing in PHP that would do this for you (this is a bit specific). Since radax is just a siad, you just need to write a function

function getParts($string, $positions){
    $parts = array();

    foreach ($positions as $position){
        $parts[] = substr($string, 0, $position);
        $string = substr($string, $position);
    }

    return $parts;
}

Something like that. Then you can use it wherever you want, so it is cleared:

$parts = getParts('some string', array(1, ... 161));

, :

^.{1}.{18} <lots more> .{161}$

, .

+7

@jay :

 $regex="/(.{1})(.{18})(.{32})(.{41})(.{108})(.{125})(.{137})(.{152})(.{161})/";
 preg_match($regex,$myfixedlengthstring,$arr);

$myfixedlengthstring - , $arr

+2

A slightly more flexible option, useful for analyzing ASCII tables with fixed records:

function ParseIrregularString  ($string, $lengths)
{ 
$parts = array(); 

foreach ($lengths as $StringKey => $position)
    { 
    $parts[$StringKey] = substr($string, 0, $position); 
    $string = substr($string, $position); 
    } 

return $parts; 
} 

By sending the following:

$string = "abcdefghiklmnopqrstuvz";
$lengths = array ("field1"=>4, "field2"=>3, "field3"=>5, "field4"=>2);
print_r (ParseIrregularString ($string, $lengths));

returns:

Array ( [field1] => abcd [field2] => efg [field3] => hiklm [field4] => no )
0
source

All Articles