从txt文件中的字符串中删除行

时间:2020-04-21 18:54:16

标签: php

目前,我有一个代码,该代码显示txt文件中的数据,并在将其转换为数组后将其随机化。

$array = explode("\n", file_get_contents('test.txt'));
$rand_keys = array_rand($array, 2);

我试图做到这一点,以便在显示此随机值之后。

$search = $array[$rand_keys[0]];

我们可以将其存储到另一个txt文件中,并将其从我们先前的completed.txt文件中删除。这是我尝试过的方法,肯定无法解决问题。

txt

然后还原到辅助文件中,我搞砸了。

$a = 'test.txt'; 
$b = file_get_contents('test.txt'); 
$c = str_replace($search, '', $b); 
file_put_contents($a, $c); 

这实际上似乎在某种程度上可以正常工作,但是当我查看文件$result = ''; foreach($lines as $line) { if(stripos($line, $search) === false) { $result .= $search; } } file_put_contents('completed.txt', $result); 时,所有内容完全相同,并且completed.txt中留有一堆空格< / p>

1 个答案:

答案 0 :(得分:2)

有一些更好的方法(恕我直言),但是此刻,您只是删除了实际的行而没有换行符。您可能还会发现它将替换其他行,因为它只是替换了文本而没有任何内容的提示。

但是您可能会通过替换新行来修复代码...

$c = str_replace($search."\n", '', $b); 

另一种替代方法是...

$fileName = 'test.txt';
$fileComplete = "completed.csv";

// Read file into an array
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
// Pick a line
$randomLineKey = array_rand($lines);
// Get the text of that line
$randomLine = $lines[$randomLineKey];
// Remove the line
unset($lines[$randomLineKey]);
// write out new file
file_put_contents($fileName, implode(PHP_EOL, $lines));

// Add chosen line to completed file
file_put_contents($fileComplete, $randomLine.PHP_EOL, FILE_APPEND);