I have a string for which I am provided a string index.
I am creating a process to read it and I am wondering if there is a php function that exists that I have overlooked or an unaware of to perform this process far more easily.
$data:
Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................
FOCF219611 CUSTOMER -0.02 8050 TOOLS & SUPPLIES - SERVICE
FOCF219669 CUSTOMER -14.49 8050 TOOLS & SUPPLIES - SERVICE
$fieldIndexes:
Array (
[0] => 15
[1] => 20
[2] => 12
[3] => 10
[4] => 50
)
Split $data
into $headers
array:
array_push($headers, substr($data, 0, $fieldIndexes[0]));
array_push($headers, substr($data, $fieldIndexes[0], $fieldIndexes[1]));
array_push($headers, substr($data, $fieldIndexes[1], $fieldIndexes[2]));
array_push($headers, substr($data, $fieldIndexes[2], $fieldIndexes[3]));
array_push($headers, substr($data, $fieldIndexes[3], $fieldIndexes[4]));
Is there a function that can remove part of a string - like array_shift
for a string?
I was thinking I could loop the $fieldIndexes
, extract the first length from the start of the string, and so on until the string is empty and condense this into 3 lines and make it portable for any number of fieldIndexes?
Desired Result:
Array
(
[HEADERS] => Array
(
[0] => Invoice No
[1] => Sale Type Desc
[2] => Misc Amt
[3] => Misc Acc
[4] => Misc Acc Desc
)
[1] => Array
(
[Invoice No] => FOCF219611
[Sale Type Desc] => CUSTOMER
[Misc Amt] => -0.02
[Misc Acc] => 8050
[Misc Acc Desc] => TOOLS & SUPPLIES - SERVICE
)
)
You can create a function like this one to split using the chunk sizes.
Note: Since each size in the $fieldIndexes
array didn't include the space between columns, I added one to each length (15+1, 20+1, ...)
<?php
$headerString ="Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................";
$fieldIndexes = [ 15+1, 20+1, 12+1, 10+1, 50+1];
function getParts($string, $positions){
$parts = array();
foreach ($positions as $position){
$parts[] = substr($string, 0, $position);
$string = substr($string, $position);
}
return $parts;
}
print_r(getParts($headerString, $fieldIndexes));
?>
Result:
Array
(
[0] => Invoice No.....
[1] => Sale Type Desc......
[2] => Misc Amt....
[3] => Misc Acc..
[4] => Misc Acc Desc.....................................
)