Forum Moderators: coopster

Message Too Old, No Replies

Removing " (quotes)

         

bsnrjones

3:52 pm on Jun 30, 2004 (gmt 0)

10+ Year Member



I have the php script, of which a portion is shown below. It runs fast as is almost working perfectly. However the tab delimited file I am importing has two field that use " (quotes) around the field information.

I need to have those removed.

Can anyone show me what I need to add and where it should go?

Here is the portion of the file in question:

$fcontents = file ('./InvStatFile.txt');
# expects the csv file to be in the same dir as this script

for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i]);
$arr = explode("\t", $line);
#if your data is comma separated
# instead of tab separated,
# change the '\t' above to ','

$sql = "insert into products_temp values ('".
implode("','", $arr) ."')";
mysql_query($sql);
echo $sql ."<br>\n";
if(mysql_error()) {
echo mysql_error() ."<br>\n";
}
}

ANY help would be very appreciated! I have messed with several commands, but I cannot get it to work. Thanks!

Burke

httpwebwitch

4:13 pm on Jun 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if every row has "" around the data, you can strip the beginning and end off it like a string

$data='abcdefgh';
$data = substr($data,1,-1);
// returns 'bcdefg'

If you just want to remove quotes indiscriminantly, use str_replace():

$data='"abcdefgh"';
$data = str_replace('"','',$data);
// returns 'abcdefgh'

If your data has valid quotes in it, this regex pattern will remove quotes only if they're found at the start or end of the string:

$data='"abc"def"gh"';
$data = preg_replace('/^\"(.*)\"$/','\${1}',$data);
// returns 'abc"def"gh'

That last regex pattern was just off the top of my head, it might need some tweaking

good luck!

bsnrjones

4:43 pm on Jun 30, 2004 (gmt 0)

10+ Year Member



Please forgive my complete newbiness!

Where exactly would I put this code in my script that I provided?

BTW- I will be using the stringreplace option.

httpwebwitch

4:51 pm on Jun 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i]);
$arr = explode("\t", $line);

[b]foreach($arr as $k=>$v){
$arr[$k]=str_replace('"','',$v);
}[/b]

$sql = "insert into products_temp values ('".
implode("','", $arr) ."')";
mysql_query($sql);
echo $sql ."<br>\n";
if(mysql_error()) {
echo mysql_error() ."<br>\n";
}
}

The foreach loop goes through the array and yanks the quotes out of each element. Then it's all tidy and ready to go into the database.

cheers,
httpwebwitch

bsnrjones

5:26 pm on Jun 30, 2004 (gmt 0)

10+ Year Member



Thanks a ton for you help! I am starting to understand how these little scripts are working.

Burke