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

Php 需要从文本文件中获取多行并与句子进行比较,php,Php,我编写了PHP代码来检查一个单词是否在句子中 我编写了以下代码: <?php $text = "I go to school"; $word = file_get_contents("bad.txt"); if (strpos($text,$word)) { echo 'true'; } ?> 如何让代码对照句子检查每行上的单词,而不是只检查一行?使用循环一次检查每行,如下所示: $text = "I go to school"; $file = file("bad.tx

我编写了PHP代码来检查一个单词是否在句子中

我编写了以下代码:

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

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

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

$text = "I go to school";
$file = file("bad.txt");

foreach($file as $line) {
    if (strpos($line, $text) !== false) {
        echo 'true';
    }
}
Edit1:file_get_content()到file()

Edit2:交换strpos()的参数

编辑3:使用: strpos($line,$text)!==假的

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

试试这个:

$text = $_GET['name'];
$file = file("bad.txt");

foreach($file as $line) {
    if (strpos($text, $line) !== false) {
        echo 'Found';
        exit;
    }
}
echo 'Not Found';
Edit5:结果是“\n”控制字符包含在行中。所以您需要使用strpos($text,trim($line)!==false)


我的错误,检查编辑的帖子,使用file()而不是file\u get\u contents()@tryharder。要使此解决方案起作用,请将
file\u get\contents()
替换为
file()
,以获取行数组。另一方面,不要只写
if(strpos($text,$line))
,还要写
if(strpos($text,$line)==TRUE)
,否则如果在文本中的位置0,一个单词就不会被识别。但是伙计们,我已经选择了通过get请求来获取句子,就像在这段代码中一样,但它似乎不起作用,有什么想法吗?在strpos($text,$line)中,您需要将参数交换为strpos($line,$text)。另外,对于if语句,请使用if(strpos($line,$text)!==false){…}我已经测试了您的代码,似乎不起作用!txt文件是:go hi hello
$text = $_GET['name'];
$file = file("bad.txt");

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

foreach($file as $line) {
    if (strpos($text, trim($line)) !== false) {
        echo 'Found';
        exit;
    }
}
echo 'Not Found';