简体   繁体   中英

Write PHP to find a word in a text file using a loop

Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.

The JavaScript part is correct but I'm having trouble with 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);
?>

If it's only 50 words then just make an array out of it and check if it's in the array.

$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;
}

You are not searching the "word" into your code, but maybe the code below will help you

$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

here is something fancy, regular expression :)

$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
}

remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.

here is a working example : http://ideone.com/LmgksA

You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.

$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";
}

This matches any word token in a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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