[英]Remove Line from String within txt file
目前我有一個代碼,它顯示來自 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
時,所有內容都完全相同,並且在test.txt
中留下了一堆空格
有一些更好的方法(恕我直言),但目前您只是刪除沒有換行符的實際行。 您可能還會發現它會替換其他行,因為它只是替換文本而不知道內容。
但是您可能會通過添加替換新行來修復您的代碼...
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.