我有一个“names.txt”文本文件,其中包含 John、Mike、Julia 等名称。现在,我在现有的“names.txt”文件中以追加模式输入另一组名称,例如 Steve、Ben、Mike。 如何限制 php 中的“Mike”重复条目?或者我怎样才能提示类似“Mike,名字已经存在”的错误信息。请输入另一个名称,以免重复。
代码是
<!DOCTYPE html>
<html>
<head>
<title>Form Page</title>
</head>
<body>
<form action="Files.php" method="POST">
<textarea rows="15" cols="30" value="textbox" name="textbox"></textarea></br>
<input type="submit" value="Save" name="Save">
<input type="submit" value="Fetch" name="Fetch">
</form>
</body>
</html>
<?php
/*** Get names from 'names.txt' file and prints the names stored in it ***/
if(isset($_POST['Fetch'])){
$file_names = "names.txt";
$current_names = file_get_contents($file_names);
echo nl2br($current_names);
}
/*** Get names from text box and Put to the 'names.txt' file in append mode ***/
if(isset($_POST['Save'])){
$current_names = $_POST["textbox"];
file_put_contents("names.txt", PHP_EOL.$current_names, FILE_APPEND);
/*** Get names form 'names.txt' file and prints the names stored in it ***/
$file_names = "names.txt";
$current_names = file_get_contents($file_names);
echo nl2br($current_names);
}
?>
最佳答案
当使用 PHP_EOL
分隔文本文件条目时:
(注意 - PHP_EOL
的输出取决于运行 PHP 的操作系统!)
//new name to insert if not in file:
$new_name = "Martin";
$file_content = file_get_contents('names.txt');
//names into array elements
$content_array = explode(PHP_EOL, $file_content);
//trim spaces and stuff from the data in your array:
foreach($content_array AS $key => $value)
{
$content_array[$key] = trim($value);
}
if(in_array($new_name, $content_array)) echo "name found - don't save it again";
关于php - 如何将重复数据输入限制为 PHP 文本文件中的现有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326707/