मुझे लगता है कि फ़ाइलों के साथ काम करने का सबसे अच्छा तरीका उन्हें तारों के रूप में संपादित करना है।
पहले, फ़ाइल के सभी लाइनों (निम्नलिखित कोड संकुचित किया जा सकता है) हो:
$file = @fopen($dir, 'r'); # As you said, $dir is your filename
if ($file) { # Ending bracket is at the end
if (filesize($dir)) { # Checks whether the file size is not zero (we know file exists)
$fileContent = fread($file, filesize($dir)); # Reads all of the file
fclose($file);
} else {
// File is empty
exit; # Stops the execution (also you can throw an exception)
}
$fileLineByLine = explode(PHP_EOL, $fileContent); # Divides the file line by line
यहाँ, आप अपने खोज कर सकते हैं:,
$key = false; # By default, your string $line is not in the file (false)
foreach ($fileLineByLine as $lineNumber => $thisLine)
if ($thisLine === $line)
$key = $lineNumber; # If $line found in file, set $key to this line number
, बस आप लाइन $ निकाल सकते हैं कुंजी + 1:
if ($key !== false) # If string $line found in the file
unset($fileLineByLine[$key]); # Remove line $key + 1 (e.g. $key = 2, line 3)
अंत में, आप फाइल करने के लिए अपने परिवर्तनों को सहेजने चाहिए:
$newFileContent = implode(PHP_EOL, $fileLineByLine); # Joins the lines together
$file = fopen($dir, "w"); # Clears the file
if ($file) {
fwrite($file, $newFileContent); # Saves new content
fclose($file);
}
} # Ends 'if ($file) {' above
इसके अलावा आप एक फ़ंक्शन के रूप में कोड ऊपर सेट कर सकते हैं।
नोट्स:
$ लाइन \ N की तरह नए लाइन वर्ण नहीं होने चाहिए। आप उन्हें निकालना होगा:
$line = str_replace(PHP_EOL, '', $line);
-
$fileLineByLine[$key] = "";
unset($fileLineByLine[$key]);
के बजाय
का उपयोग न करें, क्योंकि पहले मामले लाइन को दूर नहीं करता है, यह सिर्फ लाइन को साफ करता है (और एक अवांछित खाली रेखा बनी रहेगी)। उस स्थिति में, implode() $ fileLineByLine [$ key] के लिए भी एक नई पंक्ति जोड़ता है जो खाली है; अन्यथा यदि आप एक चर को अनसेट करते हैं, तो यह अनुपलब्ध होगा (और implode() इसे नहीं ढूंढ सकता)।
awk एक बाहरी कार्यक्रम है, आप क्या awk के बारे में कार्यकारी या इसी तरह के समारोह – Raisen