[英]Search file for word and delete line
這是同一主題的第二個要求。 我不清楚我是否需要刪除該行。
我在這里搜索,發現腳本的一部分,該腳本應該搜索一個單詞並刪除該行。 我嘗試執行的操作似乎有點錯誤。
我在下拉菜單中有一個選項列表。 我希望它刪除選擇的行。 調用下面的php時,從下拉頁面調用的文件choice.php似乎已釋放,因為沒有訪問被拒絕或違反錯誤。
這些是我被告知需要添加的最后3行后得到的錯誤。
fopen() expects at least 2 parameters, 1 given
implode(): Invalid arguments passed
fwrite() expects parameter 1 to be resource, boolean given
fclose() expects parameter 1 to be resource, boolean given
提前致謝
<?php
// Separate choice.php has the following pull down
// Select item to delete from list
// <option value="item1.php">Item 1</option>
// <option value="item2.php">Item 2</option>
// ...... many items.
$workitem = $_POST["itemtodelete"];
$file = file("option.list.php");
foreach( $file as $key=>$line ) {
if( false !== strpos($line, $workitem) ) {
unset ($file[$key]);
}
}
// Removed "\n"
$file = implode("", $file);
// Told to add this.
$fp = fopen ("option.list.php");
fwrite($fp,implode("",$file);
fclose ($fp);
?>
fopen
需要$mode
作為第二個參數,因此會失敗,並且需要$fp
所有內容。
只需使用file_put_contents
。 它甚至會為您內implode
數組:
$workitem = $_POST["itemtodelete"];
$file = file("option.list.php");
foreach( $file as $key=>$line ) {
if( false !== strpos($line, $workitem) ) {
unset ($file[$key]);
}
}
file_put_contents('option.list.php', $file);
好。 您缺少一些右括號以及其他內容。
$replaceItem = $_POST['itemtodelete']; // You should filter this data
$newContents = "";
$path = PATH_TO_FILE; // This could be hard coded, but not recommended
$filename = "option.list.php";
// Check to see if the file exists
if ( file_exists($path."/".$filename) ) {
// Wrap our IO stuff so we catch any exceptions
try {
// Open the file for reading
$fp = fopen($path."/".$filename, "r");
if ($fp) {
// Loop line-by-line through the file
while($line = fgets($fp, 4096) !== false) {
// Only add the line if it doesn't contain $replaceItem
// This is case insensitive. I.E. 'item' == 'ITEM'
// For case sensitive, use strstr()
if ( stristr($line, $replaceItem) == false ) {
$newContents .= $line;
}
}
}
// Close our file
fclose($fp);
// Replace the contents of the file with the new contents
file_put_contents($path."/".$filename, $newContents);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
編輯:試試這個。 我做了一些修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.