View Full Version : adding data from a text file to a database

02-20-2009, 03:10 AM
I already know how to use arrays, but I'm wondering how I would only take certain text out of a text file to add to a table. For example if I had a list(more than 10 digits per line) such as:

bats rats cats hats
coils boils soils toils
make fake bake take

and wanted only to get the third item out of each line how would I do this? I believe I would have to put the info into an array using file (), but I'm not sure how to select specific parts of the array for adding to the fields. I would really appreciate some help with this.

02-20-2009, 09:33 PM
Ok well I think I have this figured out, but I'm having some trouble with something else. I'm trying to use str_replace() to get rid of a bunch of useless text in a file I have. The problem is, the text file contains code and I think it is messing with my results. I have this so far:

$string = "<td style="width:150px;">Data1&nbsp;</td><td style="width:150px;">Data2&nbsp;</td><td style="width:150px;">Data3&nbsp;</td>";

$replace = array("<td style="width:150px;">", "&nbsp;</td>");

$result = str_replace($replace, "", $string)

echo $result;
I think the reason it doesn't work is because the values in $string are not valid? Am I doing this the right way, or is there an easier method? I'm completely new to this so maybe it is something obvious?

I've been looking into preg_replace, but I'm not really sure that would solve my problem.

02-20-2009, 11:16 PM
I've now come to this, but I'm getting a parse error on the line where I define $datapattern. I'm using a tutorial where they access $contents variable by getting a webpages sourcecode, but I don't see how that could make a difference. Any help would be appreciated.

$contents = '/<td style="width:150px;">Data1&nbsp;</td><td style="width:150px;">Data2&nbsp;</td><td style="width:150px;">Data3&nbsp;</td>/';

$datapattern = "/<td style="width:150px;">([a-zA-Z0-9]*)</td>/";

preg_match($datapattern, $contents, $data);

echo $data[0];
echo $data[1];
echo $data[2];

02-21-2009, 12:05 AM
Hey I think I've got it.

$contents = '<td style="width:150px;">Data1&nbsp;</td><td style="width:150px;">Data2&nbsp;</td><td style="width:150px;">Data3&nbsp;</td>';

$data_pattern = '~<td style="width:150px;">([a-zA-Z0-9]*)&nbsp;</td>~';

preg_match_all($data_pattern, $contents, $data, PREG_SET_ORDER);

echo $data[0][0];
echo $data[1][0];
echo $data[2][0];

This yields the result I've been looking for.

02-21-2009, 07:41 AM
hi mate

its like you have just helped yourself