How to trim values from lines of a CSV file with PHP

I have been working on a tool for work for almost a year. Here is some sample data.

Here is what I have:

Reference:
Route, Address, City, PubCode, Copies, FOD, Status, Account Number

XX0001,1234 CENTRAL AVE,CHICAGO,CT,1,SMTWTFS,ACTIVE,0000112 < new line >
XX0001, 2345 HERITAGE LN,CHICAGO,CT,1,S_____S,ACTIVE,5235234 < new line >
XX0001, 3456 JOY ST,CHICAGO,CT,1,SMTWTFS,ACTIVE,6434686 < new line >

This data is currently stored in an array like $route[‘XX0001’] = <insert above contents with as value. The next key would be another delivery route number, followed by data associated with that delivery route.

Then I save it to a file.

I want to be able to trim XX0001 and ACCOUNT NUM from each line with regex without having to break the array values apart by < new line > and then by comma… I just can’t wrap my brain around that.

Is there a way to trim the first and last segment from each line… going through every line of the array value without running a loop on each line of data in the array value?

Did any of that make sense? Haha

Each time you input a line as an array from your CSV file, could you use array element 0 for the first, and use the count() function to figure out the index of the last one?

ETA - sorry, I misread it, I didn’t realise you wanted to use regex.

I think there will need to be a loop somewhere. Either writing your own or maybe using something like ArrayIterator and loop “behind the scenes”.

Why the aversion to using a loop?

Oh I get confused because of the data. I found a solution with preg_replace. :slight_smile:

1 Like

would you show some insights for other people encountering the same problem?

$new_line_data = preg_replace('/(.*),(.*),(.*),(.*),(.*),(.*),(.*),(.*)/', '$2,$3,$4,$5,$6,$7', $routelist_contents[$i]);

I just put that in my loop… I’m not using $1 or $8 so this works for what I was trying to accomplish. Still very messy… and I’m just awful with RegEx.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.