March 30, 2012

Parsing text files in javascript/php?

Question by user851262

Here is my file: http://www.mediafire.com/?17bggsa47u4ukmx
It is basically a text file with a different extension.

It is a test that i am building a test reader for in html/javascript/php.
I want it to read the $$0 meaning the first question and then get the next line of content after it, which will always be a question.

My code:
In php:

$lines = file("hlm08.dat"); //file in to an array
// Make it search the whole file possible using a while loop by replacing the $$0
if (in_array("$$0", $lines)) {
    echo "I found first Question Number";
    /// Code to find the question right after it
}

Part of file:

Hotel and Lodging Management
I
$$0

What do some hotel chains develop to establish formal relationships with employees?

A. Applications 
B. Regulations 
C. Policies
D. Contracts


/D
Contracts. Contracts are agreements between two or more people or organizations
stating that one party is to do something in return for something provided by
the other party. Employment contracts usually specify what an employee is
expected to do in exchange for being compensated by the hotel chain. These
contracts are often considered legal agreements that establish formal
relationships with employees. Hotel chains often develop regulations and
policies that employees are expected to follow, but these do not establish
formal relationships with the employees. Applications are forms that potential
employees fill out to apply for jobs.
$$1

An impact of antitrust legislation on business is that it prevents hospitality
businesses from

A. experiencing growth. 
B. being competitive. 
C. raising prices.
D. forming monopolies.

I am not sure how to make it scan the whole file and put all the questions in an array. the questions come right after each $$0 (number of the question).

Answer by Starx

I suppose foreach can do what you are trying

$lines = file('hlm08.dat');

foreach ($lines as $line_num => $line) {
    if($line == '$$0') {
         echo $lines[$line_num+1]; //'get the next line
    }
}

Update:

But after you update, extract the content using regex might be better.

$text = file_get_contents('hlm.dat');
preg_match_all('/$$[0-9](.*?)$$/', $text, $matches);
print_r($matches);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!