繁体   English   中英

编写PHP以使用循环在文本文件中查找单词

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM