I have a file named "test.txt" inside it has several words, I have an input where I get the inserted word and would like to check if this word is contained within this ".txt file".
Does anyone know how to do this?
I have a file named "test.txt" inside it has several words, I have an input where I get the inserted word and would like to check if this word is contained within this ".txt file".
Does anyone know how to do this?
PHP
if( strpos(file_get_contents("texto.txt"),$_POST['palavra']) !== false) {
echo "tem";
}else{
echo "não tem";
}
HTML
<form action="" method="post">
<input type="text" name="palavra">
<input type="submit" name="botao" value="Verificar">
</form>
strpos - Find the position of the first occurrence of a string
file_get_contents is the preferred method to read the content of a file in a string.
<?php
$linhas= file("C:\Documents and Settings\myfile.txt");
foreach($linhas as $linha)
{
echo($linha);
/* Aqui compara a string */
}
?>
Or if you know the line where the word is
$arq = fopen($arquivo, 'r');
while (!feof($arq)) {
$linha = fgets($arq); // cria um array com o conteudo da linha atual do arquivo
if ((substr($linha, 23, 1) == 'palavra') ) {
/* 23 - onde começa a palavra */
/* 1 - número de letras */
/* faz o que precisa */
}
}
In this way, PHP passes line by line, so you just have to compare with a regex or string if the word is equal.
Hello, you can use file_get_contents in conjunction with strpos and the strtolower of PHP.
Here is an example of how it can be done:
<?php
$arquivo = strtolower(file_get_contents('teste.txt'));
$textoBuscar = strtolower($_POST['nome_do_input']);
if(isset($_POST)) {
if(strpos($arquivo, $textoBuscar) !== FALSE) {
echo '<h1>Existe a palavra ' . $_POST['nome_do_input'] . ' no teste.txt</h1>';
} else {
echo '<h1>Não Existe a palavra ' . $_POST['nome_do_input'] . ' no teste.txt</h1>';
}
}
?>
<form method="POST">
<input type="text" placeholder="Digite o que deseja consultar" />
<input type="submit" value="Buscar" />
</form>