5.7 Extracting Specific Lines


You want to extract all lines from one starting pattern through an ending pattern, or something from a starting number to an ending number. For instance, you wanted to start operating on a newsgroup file only after all the headers had been stripped.

Technique

Use a Boolean value and some if statements:

 <?php $in_range = false; while ($line = @fgets ($fp, 1024)) {     if (!$in_range && ereg ("beginpattern", $line)) {         $in_range = true;     } elseif (ereg ("endpattern", $line)) {         break;     }    if ($in_range) {          //..do if condition met         // here's where we operate on $line    } } ?> 

Comments

In the code, we simply match each line of the input against the beginning pattern, and once we find it, we set $in_range variable to true . Subsequently, the special code is executed on every line of the input until we match against the ending pattern. This could easily be modified so that it incremented through a range of line numbers :

 <?php $start_line = 4; $end_line   = 10; $i  = 0; while ($line = @fgets ($fp, 1024)) {     if ($i >= $start_line && $i <= $end_line ) {         // .. Do what you want to do here     } elseif ($i > $end_line) {         break;     }     $i++; } ?> 

One place this is useful is when parsing newsgroup messages. The following script will parse a newsgroup message and output the body to the browser:

 <html> <head>     <title> News-mess.txt body </title> </head> <body> <?php $fp = @fopen ("news-message.txt", "r") or                 die ("Cannot open news-message.txt"); $blanks = 0; while ($line = fgets($fp, 1024)) // 1kb buffer {     if (ereg("^[[:space:]]*$", $line)){         $blanks++;     }     if ($blanks >= 2) {         print nl2br (htmlspecialchars ($line));     } } @fclose($fp) or die("Cannot close news-message.txt"); ?> </body> </html> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net