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

时间:2016-01-10 22:09:23

标签: php

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

我已经写了这段代码:

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

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

test
hola
owb

如何使代码检查每行上的单词而不是一行?

1 个答案:

答案 0 :(得分:1)

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

$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()的参数

Edit3:使用:     strpos($ line,$ text)!== false

编辑4:我看到我误解了这个问题。您想检查输入是否包含存储在文件中的任何单词(而不是我假设的其他方式)。

试试这个:

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

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

编辑5:结果&#39; \ n&#39;控制字符包含在该行中。所以你需要使用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';