2013-05-07 50 views
1

我做了一个简单的形式与textfields,当我提交按钮它wrties所有文本字段值到.txt文件。这里是.txt文件内容的示例:导航通过txt文件与PHP,搜索和显示特定内容

----------------------------- 
How much is 1+1 
3 
4 
5 
1 
----------------------------- 

的第一个和最后一个行是有,只是单独的数据。 之后的第一行是question,底部分离器之前(1)是true answer,并且questiontrue answer之间的所有值都是false answers

我想现在做的是回声出questionfalse answerstrue answer,seperatly:

echo $quesiton; 
print_r ($false_answers); //because it will be an array 
echo $true answer; 

我认为解决的办法是strpos,但我不知道如何使用它,我希望它的方式。我可以这样做吗? :

Select 1st line (question) after the 1st seperator 
Select 1st line (true answer) before the 2nd seperator 
Select all values inbetween question and true answer 

请注意,即时通讯只显示一个例子,.txt文件有很多这些问题与-------分开。

我是否正确使用strpos解决此问题?有什么建议么?

编辑: 发现了一些功能:

$lines = file_get_contents('quiz.txt'); 
$start = "-----------------------------"; 
$end = "-----------------------------"; 

$pattern = sprintf('/%s(.+?)%s/ims',preg_quote($start, '/'), preg_quote($end, '/')); 
if (preg_match($pattern, $lines, $matches)) { 
    list(, $match) = $matches; 
    echo $match; 
} 

我觉得这可能会奏效,目前还不能确定。

回答

1

你可以试试这个:

$file = fopen("test.txt","r"); 
$response = array(); 
while(! feof($file)) { 
    $response[] = fgets($file); 
} 
fclose($file); 

这样你会得到响应阵列,如:

Array(
    [0]=>'--------------', 
    [1]=>'How much is 1+1', 
    [2]=>'3', 
    [3]=>'4', 
    [4]=>'2', 
    [5]=>'1', 
    [6]=>'--------------' 
) 
+0

并没有真正回答这个问题,但可以作为它的开始。 – Brad 2013-05-07 13:53:56

+0

谢谢,我认为这可能类似于我正在寻找的东西 – Edgar 2013-05-07 13:55:42

0

你可以尝试这样的事:

$lines = file_get_contents('quiz.txt'); 
$newline = "\n"; //May need to be "\r\n". 
$delimiter = "-----------------------------". $newline; 
$question_blocks = explode($delimiter, $lines); 
$questions = array(); 
foreach ($question_blocks as $qb) { 
    $items = explode ($newline, $qb); 
    $q['question'] = array_shift($items); //First item is the question 
    $q['true_answer'] = array_pop($items); //Last item is the true answer 
    $q['false_answers'] = $items; //Rest of items are false answers. 
    $questions[] = $q; 
} 
print_r($questions);