I am looking for ways to split a string into an array, sort of str_split()
, where the chunk sizes are dictated by an array.
I could do that by looping through the string with a bunch of substr()
calls, 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.
There is nothing in PHP that will do that for you (it's a bit specific). So as radashk just siad, you just have 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. You can then use it wherever you like, so it's clean:
$parts = getParts('some string', array(1, ... 161));
If you really wanted to, you could implode it into a regular expression:
^.{1}.{18} <lots more> .{161}$
would match what you wanted.