I have this code. It let's the user search file.txt & echo's all the results.I would like to know if there is any way to limit the amount of lines it can echo?I'm open to any suggestions, even changing the code to a different way of searching.I've tried putting it in a database, but the file isn't formatted and is 300k+ lines so it's hard to format it so it can go into a database. Thanks.
$lines = file('file.txt');
$search = $_POST['Search'];
$found = false;
foreach($lines as $line) {
if(strpos($line, $search) !== false) {
$found = true;
echo $line . "<br>";
}
I would recommend using a for loop. You may replace
foreach($lines as $line) {
if(strpos($line, $search) !== false) {
$found = true;
echo $line . "<br>";
}
with
for($i=0, $j = 0; $i <= $maximumLineNumber; $i++) {
if(strpos($lines[$i], $search) !== false && $j <= $maximumEchoNumber) {
$found = true;
$j += 1;
echo $lines[$i] . "<br>";
}
}
$lines = file('file.txt');
$search = $_POST['Search'];
$count = 0;
$MAX = 50; // Define the maximum number
$found = false;
foreach($lines as $line) {
if(strpos($line, $search) !== false)
{
$found = true;
echo $line . "<br>";
$count++;
if ($count == $MAX) { break; }
}
}
$max_lines = 30;
foreach($lines as $line_num => $line) {
if(strpos($line, $search) !== false) {
$found = true;
echo $line . "<br>";
}
if($max_lines == $line_num) break;
}
Related
I'm trying to post 3 arrays using foreach and for some reason the break at the end isn't working and it outputs the whole list (40+) on to the page.
$file = fopen('names.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
$i = 0;
foreach ($line as $number) {
{
if($i==3){ break; } else {
$rtime = mt_rand(1, 7);
echo $number; }
$i++;
}
}
}
fclose($file);
This is kind of how it looks: take.ms/cLgIh, instead it should only show 3 of these usernames.
<?php
$i = 0;
//I have opened my contact.csv :P
$file = fopen('contact.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
foreach ($line as $number) {
{
if($i==3){ exit(); } else {
$rtime = mt_rand(1, 7);
echo "<br/> i = ".$i.$number.", "; }
}
$i++;
}
}
fclose($file);
?>
I have downloade first sample CSV from here:-http://www.sample-videos.com/download-sample-csv.php
And this code works for me:-
<?php
$file = fopen('SampleCSVFile_2kb.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
$i = 0;
foreach ($line as $number) {
if($i==3){
exit;
} else {
$rtime = mt_rand(1, 7);
echo $number.'<br/>';
echo $i.'<br/>'; // you can remove this line
}
$i++;
}
}
fclose($file);
?>
Output on each page refresh:-
http://prntscr.com/cln2ju
http://prntscr.com/cln2nf
Note:- if still not work then check your CSV file. May be it is corrupted.
Conclusion:- And after all discussion it comes to an end that your CSV file is corrupted. But yes code improvement is needed too
You need to increment $i otherwise it's value will always be 0
$i = 0;
foreach ($line as $number) {
$rtime = mt_rand(1, 7);
echo "$number";
if($i==3) break;
$i++;
}
Also you need to check if your while statement is closing
$file = fopen('names.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
$i = 0;
foreach ($line as $number) {
$rtime = mt_rand(1, 7);
echo $number;
if($i==3) break;
$i++;
}
} //check for this
As I can see in your code example it is missing the closing brace
Also, remove the double quotes from your $number, it's not necessary.
echo $number
You have a mistake is that the break are in the if($i==3) and you declared $i =0, but never increment this. So $i never arrive at 3.
I have text file
name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3
i want read it and return like that
$nn = name1
$ss = willhaveishere1
with my code i get only name1
my code is
$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
This is probably what you need
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
echo substr($row, $pos + 1);
$nn[] = substr($row, $pos + 1);
} else {
echo $row;
$ss[] = $row;
}
}
}
EDIT
Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.
Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql);
}
EDIT 2
try this example:
$file = array(
0 => 'name,name1',
1 => 'willhaveishere1',
2 => 'name,name2',
3 => 'willhaveishere2',
4 => 'name,name3',
5 => 'willhaveishere3'
);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$nn[] = substr($row, $pos + 1);
} else {
$ss[] = $row;
}
}
}
echo '<pre>';
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');";
echo $sql.PHP_EOL;
}
You can try this straightforward method:
if($fh = fopen("file.txt","r")){
$nameBefore = false;
//loop through every line of your file
while (!feof($fh)){
$line = fgets($fh);
//check if the name was detected in previous line
if ($nameBefore !== false)
{
//you have the set of name and line, do what you want
echo $nameBefore . ': ' . $line . '<br />';
$nameBefore = false;
}
else
{
//see if the line is made of two coma separated segments and the first one is 'name'
//Remember the name for the next line
$parts = explode(',', $line);
if (count($parts) == 2 && $parts[0] == 'name')
$nameBefore = $parts[1];
}
}
fclose($fh);
}
One option is to use strpos to find the first occurrence of the character in the line, and if found remove everything from the line before that position. This way you are left with only the part of the line you are interested in.
Code:
$character = ',';
$fileHandle = fopen('file.txt', 'r');
while (!feof($fileHandle)) {
// Retrieve the line from the file
$line = fgets($fileHandle);
// If the line contains the character
// Remove everything before the character
$charPos = strpos($line, $character);
if ($charPos !== false) {
$line = substr($line, $charPos + 1);
}
// Do something with the remainder of the line
echo $line . PHP_EOL;
}
fclose($fileHandle);
Output:
name1
willhaveishere1
name2
willhaveishere2
name3
willhaveishere3
If you wish to retrieve the following line, simply do another retrieve line call in your loop:
while (!feof($fileHandle)) {
// Retrieve two lines in one loop iteration
$lineOne = fgets($fileHandle);
$lineTwo = fgets($fileHandle);
}
Making sure to only apply the comma replace part on the first line. This can lead to problems though if your data is... inconsistent.
Hope this helps.
I'm trying to search a PHP file for a string and when that string is found I want to return the whole LINE that the string is on. Here is my example code. I'm thinking I would have to use explode but cannot figure that out.
$searchterm = $_GET['q'];
$homepage = file_get_contents('forms.php');
if(strpos($homepage, "$searchterm") !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
Just read the whole file as array of lines using file function.
function getLineWithString($fileName, $str) {
$lines = file($fileName);
foreach ($lines as $lineNumber => $line) {
if (strpos($line, $str) !== false) {
return $line;
}
}
return -1;
}
You can use fgets() function to get the line number.
Something like :
$handle = fopen("forms.php", "r");
$found = false;
if ($handle)
{
$countline = 0;
while (($buffer = fgets($handle, 4096)) !== false)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
$countline++;
}
if (!$found)
echo "$searchterm not found\n";
fclose($handle);
}
If you still want to use file_get_contents(), then do something like :
$homepage = file_get_contents("forms.php");
$exploded_page = explode("\n", $homepage);
$found = false;
for ($i = 0; $i < sizeof($exploded_page); ++$i)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
}
if (!$found)
echo "$searchterm not found\n";
If you use file rather than file_get_contents you can loop through an array line by line searching for the text and then return that element of the array.
PHP file documentation
You want to use the fgets function to pull an individual line out and then search for the
<?PHP
$searchterm = $_GET['q'];
$file_pointer = fopen('forms.php');
while ( ($homepage = fgets($file_pointer)) !== false)
{
if(strpos($homepage, $searchterm) !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
}
fclose($file_pointer)
Here is an answered question about using regular expressions for your task.
Get line number from preg_match_all()
Searching a file and returning the specified line numbers.
I need to print out csv file into html or put a numeric data into database:
But I need to start a loop at specific position and break it at another specific position (regex).
So I need to reprint only rows with numerical data and all columns from them.
Following is pseudo-code - not working properly:
<?php
$row = 1;
$handle = fopen("test.csv", "r");
while ($data = fgetcsv($handle, 1000, ","))
{
if (preg_match('/[Morning]/', $data[0]) === 1 // start at this rwo plus two lines down )
{
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++)
{
for ($c=0; $c < $num; $c++)
{
echo $data[$c] . " ";
}
if (preg_match('/[Total Cash:]/', $data[0]) === 1)
{ break; row -1 }
}
echo "<br>";
}
}
fclose($handle); ?>
So csv goes like this:
/--some lines--/
Date: 3/3/11,
Morning,
--blank line---
Customer No,Time,CheckNo,Total,
1234,12-45,01,20.00,
1236,1-00,03,30.00,
1240,2-00,06,30.00,
--more numerical rows of data at variable length that I need to loop over--
1500,4-00,07,22.00,
----,----,---,----,
Total Cash, , , ,120.00,
/--some other lines--and it goes/
Lunch Time,
---similar like Morning above ---
Any info how to properly addrres this issue is appreciated, I can now do so many loops and regex but with this I need some more time and help. Thanks.
$lines = file('test.csv'); //read file into an array, one entry per line
$active = false; //keep track of what rows to parse
//loop one line at a time
for ($i = 0; $i < count($lines); $i++) {
$line = $lines[$i];
if (strpos($line, 'Morning') !== false) { //start parsing on the next row
$active = true;
$i += 2; //skip the blank line and header
continue;
}
if (strpos($line, '----,') !== false) { //stop parsing rows
$active = false;
}
if ($active) { //if parsing enabled, split the line on commas and do something with the values
$values = str_getcsv(trim($line));
foreach ($values as $value) {
echo $value . " "; //these are the numbers
}
}
}
$lines = file('test.csv');
$parsing = false;
foreach ($lines as $line)
{
$parsing = ((strpos($line, 'Morning') !== false) || $parsing)
&& ((strpos($line, 'Total Cash') === false);
if (!$parsing)
continue;
$values = strgetcsv($line);
echo implode(' ', $values);
}
Edit: Basically, it does the same as Dan Grossmans solution, but shorter ;-)
$lines = file('test.csv');
// Skip the unwanted lines
// Means: Every line until the line containing "Morning,"
do {
$line = array_shift($lines);
} while(trim($line) !== 'Morning,');
$lines = array_slice($lines, 2); // Mentioned something about "2 lines below" or such" ^^
// Do something with the remaining lines, until
// Line _begins_ with "Total Cash"
while(strncmp('Total Cash', trim($line = array_shift($lines)), 10) !== 0) {
echo implode(' ', str_getcsv($line)) . PHP_EOL;
}
I am trying to figure out a way to read a CSV with returns in it in PHP. The problem is when you read the file like this:
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
row data...
}
}
If you have a retun in the CSV it does not work, it just sees the returns as a new row.
My idea was to have a regex to check for unclosed quotes, but I dont know of anything like that. Any ideas?
Since it seems the built-in fgetcsv does not correctly handle the CSV standard, there are suggestions for alternatives on the PHP man page for fgetcsv - here's one of them:
From http://www.php.net/manual/en/function.fgetcsv.php
The PHP's CSV handling stuff is
non-standard and contradicts with
RFC4180, thus fgetcsv() cannot
properly deal with files like this
example ...
There is a quick and dirty
RFC-compliant realization of CSV
creation and parsing:
<?php
function array_to_csvstring($items, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
$string = '';
$o = array();
foreach ($items as $item) {
if (stripos($item, $CSV_ENCLOSURE) !== false) {
$item = str_replace($CSV_ENCLOSURE, $CSV_ENCLOSURE . $CSV_ENCLOSURE, $item);
}
if ((stripos($item, $CSV_SEPARATOR) !== false)
|| (stripos($item, $CSV_ENCLOSURE) !== false)
|| (stripos($item, $CSV_LINEBREAK !== false))) {
$item = $CSV_ENCLOSURE . $item . $CSV_ENCLOSURE;
}
$o[] = $item;
}
$string = implode($CSV_SEPARATOR, $o) . $CSV_LINEBREAK;
return $string;
}
function csvstring_to_array(&$string, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
$o = array();
$cnt = strlen($string);
$esc = false;
$escesc = false;
$num = 0;
$i = 0;
while ($i < $cnt) {
$s = $string[$i];
if ($s == $CSV_LINEBREAK) {
if ($esc) {
$o[$num] .= $s;
} else {
$i++;
break;
}
} elseif ($s == $CSV_SEPARATOR) {
if ($esc) {
$o[$num] .= $s;
} else {
$num++;
$esc = false;
$escesc = false;
}
} elseif ($s == $CSV_ENCLOSURE) {
if ($escesc) {
$o[$num] .= $CSV_ENCLOSURE;
$escesc = false;
}
if ($esc) {
$esc = false;
$escesc = true;
} else {
$esc = true;
$escesc = false;
}
} else {
if ($escesc) {
$o[$num] .= $CSV_ENCLOSURE;
$escesc = false;
}
$o[$num] .= $s;
}
$i++;
}
// $string = substr($string, $i);
return $o;
}
?>