Is there an equivalent to PERL's TIE in php? I'd like to see if a string(single word) is in a file where each line is a single word/string. If it is, I'd like to remove the entry. This would be very easy to do in Perl but unsure how I would do this in PHP.
Depending on how you read the file will determine how you remove the entry.
Using fgets
:
$filtered = "";
$handle = fopen("/file.txt", "r");
if ($handle) {
// Read file line-by-line
while (($buffer = fgets($handle)) !== false) {
if (strpos($buffer, "replaceMe") === false)
$filtered .= $buffer;
}
}
fclose($handle);
Using file_get_contents
:
filterArray($value){
return (strpos($value) === false);
}
// Read file into a string
$string = file_get_contents('input.txt');
$array = explode("
", $string);
$filtered = array_filter($array, "filterArray");
Using file
:
function filterArray($value){
return (strpos($value) === false);
}
// Read file into array (each line as an element)
$array = file('input.txt', FILE_IGNORE_NEW_LINES);
$filtered = array_filter($array, "filterArray");
Note: Each method assumes that you want to remove the entire entry if it contains a single word.