Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jan 2005
    Location
    Pittsburgh, PA
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Line-by-line text parsing (how do I skip lines?)

    I'm moving part of a program from Java to PHP, and there's some functionality I can't quite figure out how to translate.

    I'm looking for a way to parse text files line-by-line, and searching around I've found out how to do that, but I can't figure out how to control the code so that I can skip past certain lines.

    For example, my Java code works like this:
    Code:
    while (line != null) {
    	// handle empty lines and special lines
    	if (line.equals("")) { // skip empty lines
    
    		line = in.readLine();
    		continue;
    	} else if (line.contains("Stimuli;")) {
    		// populate the names array based on line following "Stimuli;"
    		line = in.readLine();
    		names = line.split("\t");
    		line = in.readLine();
    		continue;
    	} else if (line.contains("Stimulitypes;")) {
    		more stuff...
    so when I hit a line containing "Stimuli;" I can skip to the next line, perform an action on it, and then skip to the next line before re-starting my loop.

    This is something I haven't been able to find a way to do with PHP, after much searching I figure my best bet is asking people who deal with PHP on a regular basis. Any insight on how to go about this would be a huge help.

    Cheers,
    Dave
    Nice marmot.

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    One way to do it is to use fgets(). You can also use file() to load the file into an array and then loop over it, or file_get_contents() to load the entire file into a string if you prefer.

    After you get the line with a pointer or load it into a variable you can use comparison operators, or functions like empty() etc. to check the values.
    Last edited by Inigoesdr; 11-16-2007 at 01:28 AM.

  • #3
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    I would recommend using fgets, because the other solutions read the entire file at once. Which can consume quite a bit of memory with large files.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •