php中是否存在与PERL的TIE等价的东西?我想看看文件中是否有一个字符串(单个单词),其中每行都是一个单词/字符串。如果是,我想删除该条目。这在Perl中很容易做到,但不确定如何在PHP中做到这一点。
根据读取文件的方式,将决定如何删除条目。
使用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);
使用file_get_contents
:
filterArray($value){
return (strpos($value) === false);
}
// Read file into a string
$string = file_get_contents('input.txt');
$array = explode("'n", $string);
$filtered = array_filter($array, "filterArray");
使用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");
注意:如果整个条目包含一个单词,则每个方法都假设您要删除该条目。