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.
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] => ....
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With