您好我有一个文本文件,因为这个
data.txt中
data e.g. username
我需要这样才能输入$ tag
File.php
if ($username == "$data") { echo "User Found" } else{ echo "User not found";}
对此有任何帮助真的很好:)?
答案 0 :(得分:3)
此处可以使用的一种方法是我使用preg_match()
并使用\b
字边界选项和i
用于区分大小写的开关,适用于单行或多行数据。将匹配“john”或“John”作为示例。
<?php
$_POST['name'] = "john";
$var = trim($_POST['name']); // should there be a space entered
// $var = $_POST['name'];
$pattern = "/\b$var\b/i";
$fh = fopen('data.txt', 'r') or die("Can't open file");
while (!feof($fh)) {
$line = fgets($fh, 4096);
if (preg_match($pattern, $line)) {
echo "MATCH FOUND";
}
else{
echo "NOT FOUND";
}
}
fclose($fh);
但是,如果条目由空格分隔,则无法使用。即:“约翰·多伊”。
如果是这种情况,您将需要使用以下内容,stripos()
用于不区分大小写。
<?php
$_POST['name'] = "john doe";
$search = trim($_POST['name']);
// $search = $_POST['name'];
// Read from file
$lines = file('data.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(stripos($line, $search) !== false){
echo "Found: " . $line; }
}
参考文献:
脚注:
答案 1 :(得分:1)
$data = file_get_contents('filehere');
if($username == $data) { echo "User found"; } else { echo "User not found"; }
user_pass.txt:
thomas password
john password2
代码:
<?PHP
$data = fopen('user_pass.txt', 'r');
while (($line = fgets($data)) !== FALSE) {
$data = explode(' ', $data);
if ($username == $data[0] && $password == $data[1]) {
echo "User found";
} else {
echo "User not found";
}
}
?>
除非我遗漏了什么?如果您收到错误,请回复。
答案 2 :(得分:0)
功能搜索:post function search in PHP
function search($search, $string) {
$pos = strpos($string, $search);
if ($pos === false) {
echo "The string '$search' was not found.";
} else {
echo "The string '$search' was found ";
echo "and exists at position $pos.";
}
}
love.txt as file
we
love
php
programming
打开文件:
$file = fopen("love.txt", "r");
调用函数搜索和函数fread打开文件'love.txt'
search("love", fread($file, filesize("love.txt")));
结果:
字符串'love'被发现并存在于第4位。