【问题标题】:Read a plain text file and get line 3 of text after underscore读取纯文本文件并获取下划线后的第 3 行文本
【发布时间】:2015-05-10 11:22:33
【问题描述】:

我有一个包含这样文本的文本文件...

test test_0000
test test test_1234
test test apple_4567
test test orange_8910

如何使用fopen打开文件,读取第3行并在php中打印“_”后面的值?

我试过这样:

<?php
$handle = @fopen("text.txt", "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
        ?>
        <div id="application"><center>
            <div><?php echo explode('_', $buffer)[1]; ?></div>
        </div>
        <?php
    }
    fclose($handle);
}
?>

这会显示“_”之后的所有行

【问题讨论】:

  • 你有没有尝试过或做过一些研究?
  • ^ 将此添加到您的问题中并展示您的工作!只是edit你的问题
  • 我看不到这里的问题,你不能数到 3 或者真正的主题是什么?

标签: php file fopen


【解决方案1】:

这应该适合你:

只需使用file() 将文件读入数组,然后使用strpos() 获取第一个_ 的位置,然后您可以从该位置获取substr(),直到行尾。

<?php

    $lines = file("file.txt", FILE_IGNORE_NEW_LINES);
    $line = 3;
    echo substr($lines[$line-1], strpos($lines[$line-1], "_") + 1); 

?>

输出:

4567

【讨论】:

  • 哇!!...这是快速而出色的响应..非常感谢.. :)
  • 还有一个问题,如果文本文件中没有文本,则会显示错误。请提供任何解决方案。
  • @Beney 只需检查您想要的线路是否存在,例如if(isset($lines[$line-1])) echo ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 2011-05-05
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多