【问题标题】:Append text to lines in text document, using PHP使用 PHP 将文本附加到文本文档中的行
【发布时间】:2011-06-09 22:03:46
【问题描述】:

如何使用 PHP 将以下文本附加到文本文档中新行的开头?

Line 1: T: my text here
Line 2: Z: my text here
Line 3: T: my text here

等等

基本上,在 T: 和 Z: 之间交替。

假设我使用某种爆炸? 谢谢

【问题讨论】:

    标签: php string file text append


    【解决方案1】:

    使用file 获取文件的每一行。然后迭代每一行,附加你的文本并使用file_put_contents保存文件

    <?php
    
    $lines = file('input-file.txt');
    
    $output = '';
    $TorZ = 'T';
    foreach ($lines as $line)
    {
        $output .= $TorZ.': '.$line.PHP_EOL;
    
        if($TorZ == 'T')
            $TorZ = 'Z';
        else
            $TorZ = 'T';
    }
    
    file_put_contents('output.txt', $output);
    ?>
    

    【讨论】:

      【解决方案2】:

      如果它在文件中,使用file() 读取文件,你会得到行数组。如果是字符串,请使用explode("\n", $string)。如果不知道分隔符,可以使用preg_split("/(\n|\r|\n\r)/", $string)。然后循环遍历数组的元素并添加字符串,然后使用join("\n", $arr) 将数组转换回字符串。如果您需要保留分隔符,请使用上面的 preg_splitPREG_SPLIT_DELIM_CAPTURE 选项,并在添加字符串时跳过分隔符。

      如果您使用file(),则行尾已经存在,因此请使用file_put_contents("newfile", join('', $arr)) 将其写回。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        • 2021-09-03
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多