PHP: problems searching text in a file - php

I think i was doing halfway good to get this to halfway work. Anyways the following code works to find it on the first line, but i have a script that creates each on an individual line.
Please revise or create a completely new version of the following to make it to search for the form data on every line.
$search = $_POST['search'];
$file = file("SLIST.txt");
foreach($file as $line)
{
$line = trim($line);
if($line == $search)
{
echo $search . " WAS found in the database";
}
else
{
echo $search . " was NOT found in the database";
}
}
by form i mean there is a search form on the previous page. This page is the page where it tells you whether the text put into the search form matches a line in the file (ex: Line 1: BOOT Line 2: Tree Search entry: Tree Echo msg: Tree WAS found in the database.)
It is currently not working like i intended.

If you only want to know if the search string was in the file, and don't care on which line, then strpos() (doc) with file_get_contents() might be for you like this:
$file = file_get_contents('SLIST.txt');
$search = $_POST['search'];
if (strpos($file,$search)){
echo $search . " WAS found in the database";
}
else
{
echo $search . " was NOT found in the database";
}
If you want to know the line, your solutions should work as well if you change the if($line == $search) with my strpos().
If the line has to be exactly the search query you are looking for, then your solution should work just fine

It isn't so clear. I suppose the following is what you wanted.
<?php
$search = $_POST['search'];
$file = file("SLIST.txt");
$found = false;
foreach($file as $line) {
$line = trim($line);
if($line == $search) {
$found = true;
break;
}
}
if ($found)
{
echo $search . " WAS found in the database";
}
else {
echo $search . " was NOT found in the database";
}
?>

Are you looking to find a single string in an entire file. i know you want to look on every line but this is more efficient.
Try this
$file = file_get_contents("SLIST.txt");
if(strpos($file, $search))
{
echo $search . " WAS found in the database";
}
else {
echo $search . " was NOT found in the database";
}
If you just want to read lines then do
if(strpos($line, $search))
{
echo "found";
}
else
{
echo "not found";
}

Related

if $string found break else add new not working

I am doing something wrong?
This doesn't take any effects
$id = $_POST['id'];
$tudof = "\n #QTP ".$qtp." ID: ".$id;
echo "\n";
$fp = fopen('../../../ids.txt', 'a+');
$searchString = "id";
if(exec('grep '.escapeshellarg($searchString).' '.$fp)) {
break;
} else {
// Add the new name
fwrite($fp, $writef);
fclose($fp);
}
How to search a string and if not found add a new name?
I believe this will work.
I use file_get_contents to load the file as one string and use strpos to find "id".
I also include a preg_match version since strpos will match "lid" for "id" which preg_match won't.
$id = $_POST['id'];
$tudof = "\n #QTP ".$qtp." ID: ".$id;
echo "\n";
$str = file_get_contents('../../../ids.txt');
$searchString = "id";
if(strpos($str, $searchString) !==false) {
// Found it! Break won't work.
// If you want to stop all php code use exit;
} else {
// Add the new name
// Not sure what you do here but use file_put_contents
file_put_contents('../../../ids.txt', $str);
}
// Preg_match
if(preg_match("/\b " . $str ."\b/", $searchString)) {

Search CSV file and then Return specific rows from CSV file using PHP?

I know this question has been asked before but my problem is different because I need to return the specific rows after a search.
Basically, this is the scenario:
I need to search a CSV file for a specific word/string in the name column and then IF the word/string is found I need to get the row[4] and row[5] and print them in the PHP.
The CSV looks like this:
"id","ident","type","name","latitude_deg","longitude_deg","elevation_ft"
6523,"00A","heliport","Heliport",40.07080078125,-74.93360137939453,11,
So basically, I need to search by name and if found, return the latitude_deg,longitude_deg.
This is what I have so far... However, this searches the ENTIRE CSV file which makes it slightly slower and it only returns whether the CSV file contains the string/word or not...
$search = "Heliport";
$lines = file('myCsv.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE);
}
if($line_number){
echo "Results found for " .$search
} else {
echo "No results found for $search";
}
Could someone please advice on this issue? Thanks in advance.
fgetcsv is a good tool for this, it reads a CSV line and breaks it into an array.
$search = 'Heliport';
if (($fp = fopen("myCsv.csv", "r")) !== false) {
while (($row = fgetcsv($fp)) !== false) {
if($row[3] === $search) {
echo 'Found ' . $row[3] . ': ' . $row[4] . ', ' . $row[5] . "\n";
}
}
fclose($fp);
}

Write PHP to find a word in a text file using a loop

Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.
The JavaScript part is correct but I'm having trouble with PHP:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
If it's only 50 words then just make an array out of it and check if it's in the array.
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
You are not searching the "word" into your code, but maybe the code below will help you
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
here is something fancy, regular expression :)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.
here is a working example : http://ideone.com/LmgksA
You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
This matches any word token in a string.

How to put URL in array and search through array for matching string?

I am trying to search through a URL for a matching string, but the below code snippet doesn't seem to work.
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file = file($url);
if (in_array($search,$file)) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
If you are just searching for an occurrence of a string on the page, you can use
$str = file_get_contents($url);
if (strpos($str, $search) !== false) {
echo 'Success!';
} else {
echo 'Fail';
}
in_array() checks if an array member is equal to your needle.
It is improbable many websites will have a line which is equal to a only.
Also, is allow_url_fopen enabled?
That code will only find a line that has the exact $search string (likely including whitespace). If you're parsing HTML, check PHP's DOMDocument classes. Or, you can use a regex to pull what you need.
As #alex says, check is allow_url_fopen is enabled.
Also you can use strpos to search the string:
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file_content = file_get_contents($url);
if (strpos($file_content, $search) !== false) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>

php problem searching words in a text file

I use the following code to search the text file:
$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$Pos = strpos($data,$query);
if ($Pos)
{
echo "Found";
}
else
{
echo "Not Found";
}
Let the text file be:
orange_red blue_gray yellow_blue white_black
It finds red at orange_red,but i want to match the whole word.
For example:
If the text to be searched is to be red
I want it to return false because red does not exist independently it is part of word orange_red.
In brief i want to search words delimited by space
Searching red and orange should return false and searching orange_red should return true.
Split the string into an array using explode. Then search the array using array_search to see if it contains your exact word.
This is the easiest/fastest way I can think of:
$query = "red";
$FileName = "search.txt";
if(preg_match("/\b" . $query . "\b/i"), file_get_contents($FileName))
{
echo "Found";
}
else
{
echo "Not Found";
}
\b matches a word boundary, so it will only return stand-alone results for $query. preg_match returns an int denoting the number of times the pattern was found (which will be either 0 or 1, as preg_match stops after the first match - use preg_match_all to get an accurate count of how many times the pattern appears in the target).
$query="red";
$FileName = "search.txt";
foreach (explode(" ", strtolower(file_get_contents($FileName)) as $word) {
if (strtolower($query) == $word) {
$found = true;
break;
}
}
echo $found ? "Found" : "Not found";
Meh, a little less efficient, but it gets the job done.
Try this, splits the data at a space, and then sees if the query is in the array.
$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$items = explode(" ", $data);
$Pos = array_search ($query, $items);
if($Pos !== FALSE)
{
echo "Found";
}
else
{
echo "Not Found";
}
Try using strpos with " $query ", or use a regular expression and preg_match:
$query = "red";
if (strpos($data, " {$query} ") !== false) {
// data contains " red "
}
// OR
if (preg_match("/(^{$query}( )|( ){$query}( )|( ){$query}$)/", $data) === 1) {
// match found
}

Categories