Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split php string into chunks of varying length

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

I could do that by looping through the string with a bunch of substr(), but that looks neither elegant nor efficient. Is there a function that accept a string and an array, like (1, 18, 32, 41, 108, 125, 137, 152, 161), and yields an array of appropriately chopped string pieces?

Explode is inappropriate because the chunks are delimited by varying numbers of white spaces.

like image 651
aag Avatar asked Jul 08 '12 09:07

aag


2 Answers

I would use unpack():

$str = "?ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890....";
$array = unpack("a1first/a26second/a10third/a*rest",$str);
print_r($array);

This returns:

Array
(
    [first] => ?
    [second] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
    [third] => 1234567890
    [rest] => ....
)
like image 187
Aurelien M Avatar answered Oct 21 '22 03:10

Aurelien M


Just for future references the regular expressions method @jay suggested goes like this:

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

where $myfixedlengthstring is the target string and $arr gives you the result

like image 37
JuanitoMint Avatar answered Oct 21 '22 04:10

JuanitoMint