需要从一个文本文件中获取多行并与一个句子进行比较


Need to get multiple lines from a text file and compare to a sentence

我编写了PHP代码,用于检查单词是否在句子中。

我写了这个代码:

<?php 
$text = "I go to school";
$word = file_get_contents("bad.txt");
if (strpos($text,$word)) {
    echo 'true';
}
?>

但它不起作用,因为txt文件看起来像这样:

test
hola
owb

我如何让代码对照句子检查每一行的单词,而不是只检查一行?

使用循环一次检查每一行,如下所示:

$text = "I go to school";
$file = file("bad.txt");
foreach($file as $line) {
    if (strpos($line, $text) !== false) {
        echo 'true';
    }
}

第1版:file_get_content()到文件()

编辑2:交换strpos()的参数

第3版:使用:strpos($line,$text)!==错误

伊迪丝4:我明白我误解了这个问题。您想检查输入是否包含存储在文件中的任何单词(而不是像我假设的那样)。

试试这个:

$text = $_GET['name'];
$file = file("bad.txt");
foreach($file as $line) {
    if (strpos($text, $line) !== false) {
        echo 'Found';
        exit;
    }
}
echo 'Not Found';

第5版:原来"''n"控制字符包含在行中。因此您需要使用strpos($text,trim($line)!==false)。

$text = $_GET['name'];
$file = file("bad.txt");
foreach($file as $line) {
    if (strpos($text, trim($line)) !== false) {
        echo 'Found';
        exit;
    }
}
echo 'Not Found';