在一个文本文件中每一行添加一个字符的PHP操作

3
我是一名新手,有一个文本文件。文本文件的内容如下...
text1     text4     text7
text2     text5     text8
text3     text6     text9

我想做的是使用php在文本文件的前两列中的每一行都添加这个--->>>符号...我该怎么做呢...感谢您的帮助...:)..但我尝试过以下代码...
<?php
$fileContents = file_get_contents('mytext.txt');
$fixedFileContents = "--->>>";
file_put_contents($fixedFileContents, 'mytext.txt');
?>

输出应该类似于:
--->>>text1     --->>>text4     text7
--->>>text2     --->>>text5     text8
--->>>text3     --->>>text6     text9

4
你能展示一下你的输出应该是什么样子吗? - tttpapi
$data = file('mytext.txt'); foreach($data as $line) { ... } ; file_put_contents(...)。(注:这是一段 PHP 代码,用于读取名为 "mytext.txt" 的文件中的数据,并将其逐行处理后写回到文件中。) - Marc B
@user2475714 你可能想要检查一下我编辑后的版本,它与你请求的输出相同。 - h2ooooooo
3个回答

2
我不完全确定输出应该是什么,但类似这样的东西应该可以起作用:
$lines = file('mytext.txt'); 
$new = '';

if (is_array($lines)) {
    foreach($lines as $line) { 
        $new .= "--->>>" . $line;
    } 
}

file_put_contents('mytext.txt', $new);

应该给你:

--->>>text1     text4     text7
--->>>text2     text5     text8
--->>>text3     text6     text9

这基本上是我想要的...但我也希望"--->>>"在第二列中出现...感谢您的帮助.. :) - asdf
在这种情况下,您可能需要使用正则表达式(如h2oo的答案所示)。类似于这样的东西。 - Amal Murali

1
如果我理解您的问题正确,您可以使用preg_replace和正则表达式来实现此目的:
$fileContents = preg_replace('/^(\w+\s+)(\w+\s+)/m', '--->>>$1--->>>$2', $fileContents);

示例:

<?php
    $fileContents = <<<TEXT
text1     text4     text7
text2     text5     text8
text3     text6     text9
TEXT;
    $fileContents = preg_replace('/^(\w+\s+)(\w+\s+)/m', '--->>>$1--->>>$2', $fileContents);
    echo $fileContents;
?>

输出:

--->>>text1     --->>>text4     text7
--->>>text2     --->>>text5     text8
--->>>text3     --->>>text6     text9

演示


1

马克·B所说的会起作用。

$file = file('file.txt');

$contents = null;

foreach($file as $line) {

   $line = preg_replace('/\s+/', ' --->>> ', $line);
   $contents .= '--->>> ' . $line . "\r\n";

}

file_put_contents('file.txt', $contents);

你也可以使用 str_replace 来删除空格,如果你知道确切的空格、制表符或空白数量。
这应该会输出类似以下的内容:
--->>> test1   --->>> test4   --->>> test7
--->>> test2   --->>> test5   --->>> test8

编辑:糟糕,刚注意到我拥有的东西刚刚发布了!哈! 编辑2:添加替换空格以在值之间添加--->>>


这将如何在行之间添加它们? - h2ooooooo
抱歉,忘记添加一个部分。现在会进行修改。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接