I would like some assistance in creating a script that will parse a file
line by line. The file that I need to parse has a designator at the
beginning of most lines. I need the script to search for a specific
designators (listed in an array) and then send an e-mail with the
contents of each line. There will need to be a separate e-mail for each
line.
Example:
$array = array( "A120", "B120", "D120" );
Text File:
A120 Text B120 Text C120 Text D120 Text
To make this more difficult... Occasionally, one of the lines may be
followed by multiple other lines containing more information. I need to
be able to get that information as well. The only distinct part of
those lines following is that they start with 15 spaces.
Example:
D120 Text Text Text Text More Text More Text More Text
Does anyone have any ideas for me?
I would have been more impressed if you'd had a go, read some manual pages, etc etc, but I'm feeling nice today. Please read the manual on each function and try to understand how the following script works, so that we never have this conversation again, and hopefully you can help others like I've helped you. Please DON'T just use it without understanding it :)
This script could be a lot simpler and cleaner, but I've chosen to do it in three steps, so that you can see the process behind what I'm doing, and learn from it.
---The source file--- A120 Text B120 Text C120 Text D120 Text More Text A120 Text B120 Text C120 Text D120 Text More Text Even More Text Even More Text Again A120 Text ---
---The script--- <? // get text into an array $lines = file ('mydata.txt');
// grab lines starting with... $keys = array('A120', 'B120', 'D120');
// email set-up $to = '[EMAIL PROTECTED]'; $sub = 'test'; $headers = 'From: [EMAIL PROTECTED]';
/////// STEP 1 // loop through, looking for multiple lines // and glue them together foreach($lines as $number => $line) { $i = 1; while(preg_match('/^ {15}/',$lines[$number+$i])) { $lines[$number] .= $lines[$number+$i]; unset($lines[$number+$i]); $i++; } } /////// STEP 2 // loop through, deleting lines that don't match our targets foreach($lines as $number => $line) { $key = substr($line,0,4); // the first 4 chars if(!in_array($key,$keys)) { unset($lines[$number]); // delete the element } else { /////// STEP 2b // while we're here, let's delete the 15 spaces $lines[$number] = pre_replace(' {15}','',$lines[$number]); } } /////// STEP 3 // loop through remainder and send email with contents foreach($lines as $number => $line) { mail($to,$sub,$line,$headers); }
/////// STEP 4 // report echo count($lines)." email(s) sent"; ?> ---
Regards, Justin French
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php