Reputation: 259
I'm reading a textfile on the format
Phone#(tab)Text(line break) (line break)
Or more specifically
4799999999 Hey! You owe us $576.53. Pay up to account no. 9760.00.12345, ID: 201561438.
4798888888 Hey! You owe us $199. Pay up to account no. 9760.05.12345, KID: 201565173.
4797777777 Hey! You owe us... and so on.
I want to store this in a SQL database, so I need to break this apart in phone numbers and text.
Any ideas on how to split the string into pairs in PHP? And should I store these values in a Array before saving to SQL, or should I just store it right away?
Upvotes: 1
Views: 364
Reputation: 72580
I think you'd be better off using the strpos
function, in case there are tabs in the text part.
$lines = file( $filename );
foreach ( $lines as $line )
{
$tab = strpos( $line, "\t" );
$num = substr( $line, 0, $tab );
$text = substr( $line, $tab );
}
Replace the file
function and foreach
with fopen
and fgets
(see example) if the file is particularly large.
Upvotes: 1
Reputation: 4841
$data = file_get_contents ($file); // Assuming $file holds path to file
if ($data) {
$lines = explode("\n\n", $data);
foreach ($lines as $line) {
list ($phone, $message) = explode("\t", $line, 2);
// do whatever you need with it
}
}
Upvotes: 4
Reputation: 106147
Assuming the file isn't huge, you can just read the lines into an array with file()
and iterate over them like so:
$lines = file($filename);
foreach($lines as $line) {
$line_arr = explode("\t", $line, 2);
if(!empty($line_arr)) {
// $line_arr[0] will be the phone number and
// $line_arr[1] will be the text; insert them into your database
// however you please.
}
}
Upvotes: 1
Reputation: 8246
You could use Regular Expressions to break up the strings and then input them into the database using SQL.
^([0-9]{10})(.*)
would bring back the Phone Number as the first captured group, and the remaining text as the second captured group.
Upvotes: 1
Reputation: 19225
Read the file line by line, split each line on the tab car, and then put it into the DB using suitable SQL for your DB platform.
Which part are you having trouble with?
Upvotes: 6