PHP从特殊字符读取TXT文件

时间:2018-12-13 20:21:40

标签: php

我有一个TXT文件(example.txt),其中包括以下内容:

text1
text2
text3
@
new text1
new text2
new text3

PHP代码:

<?php

$open = fopen('example.txt','r');
while (!feof($open)) {
    $getTextLine = trim(fgets($open));

    if ( $getTextLine == '@' ) {
        echo fgets($open). "<br />";
    }
}

?>

如何在@字符后读取TXT文件的所有行并保存数组?我想输出的是

new text1
new text2
new text3

4 个答案:

答案 0 :(得分:1)

使用PHP的示例代码:

<?php
$input=file_get_contents("example.txt");
$lines=explode("\n",$input);
$status=false;
foreach($lines as $line)
{
    if($status === false && $line === "@")
    {
        $status=true;
    }
    else if($status === true)
    {
        echo("-->");
        echo($line);
        echo("\n");
    }
}
?>

OR

<?php
$lines = file("example.txt",FILE_IGNORE_NEW_LINES  |  FILE_SKIP_EMPTY_LINES);
$status=false;
foreach ($lines as $line)
{
    if($status === false && $line === "@")
    {
        $status=true;
    }
    else if($status === true)
    {
        echo("-->");
        echo($line);
        echo("\n");
    }
}
?>

example.txt文件:

text1
text2
text3
@
new text1
new text2
new text3

输出:

-->new text1
-->new text2
-->new text3
-->
-->

新更新:

<?php
$file = file("example.txt",FILE_IGNORE_NEW_LINES  |  FILE_SKIP_EMPTY_LINES);
$status=false;
$list=array();
foreach ($file as $line)
{
    if($status === false && $line === "@")
    {
        $status=true;
    }
    else if($status === true)
    {
        echo("-->");
        echo($line);
        echo("\n");
        $list[]=$line;
    }
}
print_r($list);
?>

数组的输出:

Array
(
    [0] => new text1
    [1] => new text2
    [2] => new text3
)

答案 1 :(得分:1)

您可以尝试以下方法:

<?php
// Read file.
$filename = 'example.txt';
$file = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Read lines
$output = array();
$found = false;
foreach ($file as $row) {
    if ($row == '@') {
        $found = true;
        continue;
    }
    if ($found) {
        $output[] = $row;   
    }   
}

// Output
print_r($output);
?>

答案 2 :(得分:1)

一个不错的简短答案是只读取整个文件,然后从PHP_EOL.'@'.PHP_EOL中提取一段文本,以确保它自己在一行上找到@。然后从开始处修剪PHP_EOL@。最后拆分为数组,使用余数爆炸...

$text = file_get_contents("a.txt");
$end = ltrim(strstr($text, PHP_EOL."@".PHP_EOL ), PHP_EOL."@");
$out = explode(PHP_EOL,  $end);
print_r($out);

如果您的文件带有...

text1
text2
text3
@
new text1
new text2
new text3
--
aaa

您可以再次使用strstr()@中选择内容,然后在--行之前...

$text = file_get_contents("a.txt");
$end = ltrim(strstr($text, PHP_EOL."@".PHP_EOL ), PHP_EOL."@");
$end = strstr($end, PHP_EOL."--".PHP_EOL, true);
$out = explode(PHP_EOL,  $end);
print_r($out);

将输出

Array
(
    [0] => new text1
    [1] => new text2
    [2] => new text3
)

答案 3 :(得分:0)

如何使用file()将文件读入内存(警告:如果这是一个很大的文件,效率可能不高),然后删除这些行,直到到达包含@的行为止

$lines = file('example.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
foreach ($lines as $i => $line) {
    if (stripos($line, '@') === false) {
        unset($lines[$i]);
    } else {
        break;
    }
}
相关问题