0

I'm trying to explode this string, so it can fit "$wpdb->insert" function in wordpress. this is the string to insert. The file contains about 42k strings like this:

(601, 'STANDARD', 'Adjuntas', '', 'Colinas Del Gigante, Jard De Adjuntas, Urb San Joaquin', 'PR', 'Adjuntas', 'America/Puerto_Rico', '787,939', '18.16', '-66.72', 'NA', 'US', 0, 0, ''),

this is the code

if ( file_exists(realpath(dirname(__FILE__)).'/install/usa_zip_codes.sql')){
                $filecontent = explode("\n",file_get_contents( realpath(dirname(__FILE__)).'/install/usa_zip_codes.sql'));
                foreach( $filecontent as $row){
                    $array = array();
                    $array = explode(", ", trim(preg_replace("/[()]/","",$row),","));
                    $wpdb->insert( 
                            $wpmyplugin_table['yp_usa_zip_codes'], 
                            array( 
                                    'zip' => $array[0], 
                                    'type' => trim($array[1],"'"),
                                    'primary_city' => trim($array[2],"'"),
                                    'acceptable_cities' => trim($array[3],"'"),
                                    'unacceptable_cities' => trim($array[4],"'"),
                                    'state' => trim($array[5],"'"),
                                   ....

but when i have strings like 'Colinas Del Gigante, Jard De Adjuntas, Urb San Joaquin', it will also split it to array elements. I've tried to explode by explode(", '", but this part , 0, 0, '' wont be split correctly. How do you deal with these things?

1 Answer 1

1

Have a look at str_getcsv. You should be able to convert

(601, 'STANDARD', 'Adjuntas', '', 'Colinas Del Gigante, Jard De Adjuntas, Urb San Joaquin', 'PR', 'Adjuntas', 'America/Puerto_Rico', '787,939', '18.16', '-66.72', 'NA', 'US', 0, 0, ''),

Into:

601, 'STANDARD', 'Adjuntas', '', 'Colinas Del Gigante, Jard De Adjuntas, Urb San Joaquin', 'PR', 'Adjuntas', 'America/Puerto_Rico', '787,939', '18.16', '-66.72', 'NA', 'US', 0, 0, ''

str_getcsv can then be used to turn the above string into an array. This will ignore commas inside of values.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes!! this one. it does the trick!!) i've replaced $array = explode(", ", trim(preg_replace("/[()]/","",$row),",")); to $array = str_getcsv(trim(preg_replace("/[()]/","",$row),","),',',"'"); and it works now. Thank you, Jim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.