duandai3964 2013-05-07 13:42
浏览 399

使用php浏览txt文件,搜索并显示特定内容

I have made a simple form with textfields, when i submit a button it wrties all textfield values into a .txt file. Here is an example of the .txt file content:

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

The 1st and last line ---- is there to just seperate data. The 1st line after the ---- is the question , the before the bottom seperator (1) is the true answer, and all the values between question and true answer are false answers.

What i want to do now is echo out the question , false answers and true answer , seperatly:

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

I think the solution is strpos , but i dont know how to use it the way i want it to. Can i do somethinglike this? :

 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

Note that im only showing one example, the .txt file has a lot of these questions seperated with -------.

Are my thoughs correct about using strpos to solve this? Any suggestions?

Edit: Found some function:

$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;
}

I think this might work, not sure yet.

  • 写回答

2条回答 默认 最新

  • doubi5520 2013-05-07 13:53
    关注

    You may try this:

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

    This way you will get response array like:

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度