[英]Write PHP to find a word in a text file using a loop
編寫PHP腳本以在文本文件(標題為a.txt)中搜索單詞。 文本文件包含50個單詞,每個單詞在一行上。 在JavaScript方面,客戶端在文本字段中鍵入一個隨機單詞,然后提交該單詞。 PHP腳本使用一個循環搜索整個50個單詞,以找到正確的單詞,直到該單詞在.txt
文件中找到為止。 如果找不到該單詞,則必須顯示一條錯誤消息,指出該單詞不在列表中。
JavaScript部分是正確的,但是我在使用PHP時遇到了麻煩:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
如果只有50個單詞,則可以從中組成一個數組,然后檢查它是否在數組中。
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = @fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
您並不是要在代碼中搜索“單詞”,但是下面的代碼可能會幫助您
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
這是花哨的,正則表達式:)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
如果您不希望搜索不區分大小寫,請從'$/im'
刪除i
那里的m
告訴解析器將^$
匹配到行尾,因此可行。
這是一個工作示例: http : //ideone.com/LmgksA
如果您要查找的只是快速的存在性檢查,則實際上不需要將文件拆分為一個數組。
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
這匹配字符串中的任何單詞標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.