提问者:小点点

删除包含某物的行(. txt-File)-使用php


我想删除包含$_POST['link']给定内容的行

它已经可以与。csv文件。此时,用于。txt-File不做任何事。

我的php代码

//txt
$txt = file('../textFiles/websites.txt');
$fpTXT = fopen('../textFiles/websites.txt', 'w');
foreach ($txt as $lines) {
  if (!str_contains($lines[2], strval($_POST['link']))) {
    fwrite($fpTXT, $lines);
  }
}
fclose($fpTXT);

带js的触发器

<!-- Delete-Function -->
    <script>
        async function deleteRequest(elem) {
            $.ajax({
                type: 'POST',
                url: '/sites/deleting.php',
                dataType: 'html',
                data: {
                    'link': elem
                }
            });
            location.reload();
        };
    </script>
</head>


<!-- Delete Icon -->
    <?php $delBtn = "<td><button class='delete' onclick=\"deleteRequest(this.parentNode.parentNode.getElementsByTagName('td')[2].innerText)\"><i class='material-icons'>&#xE872;</i></button></td>"; ?>

csv的代码(在文本代码上方)

//CSV
$csv = array_map('str_getcsv', file('../textFiles/websites.csv'));
$fpCSV = fopen('../textFiles/websites.csv', 'w');
foreach ($csv as $fields) {
  if (!str_contains($fields[2], strval($_POST['link']))) {
    fputcsv($fpCSV, $fields);
  }
}
fclose($fpCSV);

2行来自。txt文件


共2个答案

匿名用户

从< code>file()获得的“$lines”与CSV记录不是一回事。每一行都是一行,所以< code>$lines[2]引用该行的第三个字符:

$lines = "https://www.google.com\n";

$lines[2] is just a "t".

在CSV记录中,您将拥有

$lines = [ "A1", "B1", "C1", "D1" ]

and here, $lines[2] is "C1".

您应该过滤文本行以删除不需要的文本行

$outputFile = '../textFiles/websites.txt';

$remove = strval($_POST['link']);
$txt = array_filter(
    file($outputFile),
    function ($eachLine) use ($remove) {
        return !str_contains($eachLine, $remove);
        // or equivalently,
        // return false === strpos($eachLine, $remove)
        // In all cases, consider that if someone sends ".",
        // you will remove ALL sites, since they'll all have a dot in their site name.
        // So maybe is better
        // return $remove !== trim($eachLine)
        // (the "trim" is needed to get the carriage return at the end of line out of the comparison, which otherwise would always fail).
    }
);

// Now you need to write the cleaned file
file_put_contents($outputFile, implode('', $txt));

匿名用户

如果您只想替换文件中的一个单词或句子,您可以使用< code>str_replace轻松完成:

$file = '../textFiles/websites.txt';
$findText = $_POST['link'];
file_put_contents($file, str_replace($findText, '', file_get_contents($file)));