Reputation: 23
I wrote PHP code that checks if a word is in a sentence or not.
I've written this code:
<?php
$text = "I go to school";
$word = file_get_contents("bad.txt");
if (strpos($text,$word)) {
echo 'true';
}
?>
But it doesn't work because the txt file look like this:
test
hola
owb
How can I make the code check the words on each line against the sentence instead of one line only?
Upvotes: 2
Views: 662
Reputation: 944
Use a loop to check each line at a time, like so:
$text = "I go to school";
$file = file("bad.txt");
foreach($file as $line) {
if (strpos($line, $text) !== false) {
echo 'true';
}
}
Edit1: file_get_content() to file()
Edit2: swap the paramaters of strpos()
Edit3: use: strpos($line, $text) !== false
Edit4: I see I've misunderstood the question. You want to check if the input contains any of the words stored in the file (instead of the other way around as I had assumed).
Try this:
$text = $_GET['name'];
$file = file("bad.txt");
foreach($file as $line) {
if (strpos($text, $line) !== false) {
echo 'Found';
exit;
}
}
echo 'Not Found';
Edit5: Turns out the '\n' control character is included in the line. so you need to use 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';
Upvotes: 1