一个(简单(问题。我有一个用PHP编写的TXT文件搜索脚本。
$search = $_GET["search"];
$logfile = $_GET['logfile'];
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
fclose($file);
现在我要做的是删除它在TXT文件中找到的所有文本。我试着做了一个str_replace,但没有成功。
谢谢你的帮助!
我认为这将起到神奇的作用:
$file->ftruncate($file->ftell());
您需要收集不包含搜索词的行,并且需要将文本保存在数组中。
完成列表后,您需要以写入模式打开文件(这将清空文件(,然后在文件中写入收集到的文本。
这是代码:
<?php
$search = isset($_GET["search"]) ? $_GET["search"] : '';
$logfile = isset($_GET['logfile']) ? $_GET['logfile'] : '';
$text_without_term_arr = array();
if(!empty($logfile) && !empty($search)){
// Read from file
$file = fopen($logfile, "r");
echo ' <head>
<title>Searching: ' . $search . '</title>
</head>';
while(($line = fgets($file))!== false){
if(stristr($line, $search)){
// Case insensitive search
echo '<font face="Arial">' . $line . '</font><hr/>';
} else {
// Search term not found in these lines
array_push($text_without_term_arr, $line);
}
}
fclose($file);
// Empty the file and write the text again without the search term
if(!empty($text_without_term_arr)){
$new_file = fopen($logfile, "w");
$content = implode("'n", $text_without_term_arr);
fwrite($new_file, $content);
fclose($new_file);
}
}
?>
您需要另一个文件句柄来将结果写入:
$tempname=tmpname('/tmp','result');
$outfile=fopen($tempname,'w');
接下来,使用str_ireplace
删除每行中找到的文本:
$newline=str_ireplace($search, '', $line);
然后将新行写入输出文件:
fputs($outfile,$newline); // May need to send PHP_EOL too
关闭文件:
fclose($outfile);
然后将新文件重命名为旧文件名:
rename($tempname,$logfile);