我需要通过在数组中查找文本来获取数组索引号,但是然后我需要删除该数组索引并将剩下的内容传递给txt文件?
每个数组索引都是多行txt文件的爆炸物,该文件在各行中还包含其他文本(包括HTML),但在我要查找的文本的其他行中不包含任何重复。
到目前为止,我已经能够删除第一个数组索引,从而删除txt文件中的该行,但是我需要找到$ something变量所在的数组索引并删除该行...
if($_GET['delete'] == $something){
$create = fopen("info.txt", "r+t");
$oldstuff = fread($create, 1024);
$array = explode("\n", file_get_contents("info.txt"));
unset($array[$something]);
$string = implode("\n",$array);
$newstuff = fopen("info.txt", "w+");
fwrite($newstuff, $string);
fclose($newstuff);
fclose($create);
答案 0 :(得分:1)
假设info.txt
包含多行文本,并且每一行都分解为一个数组。您可以使用php函数 array_search 查找包含给定字符串的行。这样您就可以将其编写为:
if($_GET['delete'] == $something) {
$create = fopen("info.txt", "r+t");
$oldstuff = fread($create, 1024);
$array = explode("\n", file_get_contents("info.txt"));
$find = 'test'; // string you want to find
$key = array_search ($find , $array); // returns the index key if found or false if not found
if ($key) {
unset($array[$key]);
}
$string = implode("\n", $array);
$newstuff = fopen("info.txt", "w+");
fwrite($newstuff, $string);
fclose($newstuff);
fclose($create);
}
答案 1 :(得分:1)
设法做到这一点...
if($_GET['delete']){
$name = "<li class='drinks'><span class='names'>".htmlspecialchars($_GET["delete"])."</span>";
$array = explode("\n", file_get_contents("info.txt"));
$key = array_search($user , $array);
if($key !== false) {
unset($array[$key]);
};
$string = implode("\n", $array);
file_put_contents("info.txt", $string);
感谢您的帮助。意识到txt文件的每一行中的其他内容总是相同的,所以我可以将其包含在array_search中:)