分析javascript.php中的文本文件

Parsing text files in javascript/php?

本文关键字:文本 文件 javascript php 分析      更新时间:2023-09-26

这是我的文件:http://www.mediafire.com/?17bggsa47u4ukmx它基本上是一个具有不同扩展名的文本文件。

这是一个测试,我正在用html/javascript.php构建一个测试阅读器。我想让它读$$0,意思是第一个问题,然后得到它后面的下一行内容,这将永远是一个问题。

我的代码:在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
}

文件部分:

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.

我不知道如何让它扫描整个文件,并将所有问题放在一个数组中。问题紧跟在每个$$0(问题编号)之后。

我认为对于您的情况,最好的函数是explode()。因为文件中的问题由多行组成。因此,很难用一个接一个的循环线来确定整个问题

$file_content = file_get_contents("hlm08.dat");
$questions = explode("'n$$", $file_content);
print_r($questions);

试试这个

$array = array();
$lines = file("hlm08.dat"); //file in to an array
foreach ($lines as $line)
{
    if (stripos($line, "$$") !== false) 
    {
        $array[] = str_replace("$$", "", $line));
    }
}

$array 的输出

Array (
   [0] => First question
   [1] => Second question
   [2] => Third question
   .
   .
   .
etc
)

我想foreach可以做你正在尝试的

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

更新:

但是在更新之后,使用regex提取内容可能会更好。

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

Javascript版本(假设文本文件位于同一服务器上)

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $('<div />').load("hotels.txt",function() {
    var texts = $(this).text().split("$$");
    $.each(texts,function(i, data) {
      var question = $.trim(data).split('?')[0];
      $("#question").append(question+'<hr/>')    
    });
  });
});
</script>
</head>
<body>
<div id="question"></div>
</body>
</html>