+ 1
How to find string in text file from input field ? Then echo the entire line.
2 ответов
+ 1
To find a string in a text file from an input field in PHP, you can use the following steps:
1) Retrieve the input from the form using the $_POST superglobal array in PHP. For example, if your input field has the name "search_field", you can retrieve the value using $_POST['search_field'].
2) Open the text file using the fopen() function in PHP. For example: $file = fopen("path/to/textfile.txt", "r");
3) Read the contents of the file into a string variable using the fread() function. For example: $contents = fread($file, filesize("path/to/textfile.txt"));
4) Use the strpos() function in PHP to search for the input string within the contents of the file. For example: $search_term = $_POST['search_field'];
$pos = strpos($contents, $search_term);
+ 1
5) Check the result of the strpos() function to see if the search term was found in the file. If strpos() returns a non-false value, then the search term was found. For example: if ($pos !== false) {
echo "Search term found!";
} else {
echo "Search term not found.";
}
6) Close the file using the fclose() function. For example: fclose($file);
Here's the complete code example: <?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$search_term = $_POST['search_field'];
$file = fopen("path/to/textfile.txt", "r");
$contents = fread($file, filesize("path/to/textfile.txt"));
$pos = strpos($contents, $search_term);
if ($pos !== false) {
echo "Search term found!";
} else {
echo "Search term not found.";
}
fclose($file);
}
?>
<form method="POST">
<input type="text" name="search_field">
<input type="submit" value="Search">
</form>
Note: Remember to replace "path/to/textfile.txt" with the actual path to your text file.