Text File Sum of Specific Columns PHP - php

I have a txt file populated with line of numbers... I have a code wherein the user can filter particular lines in the txt file
CODE for FILTERING:
<?php
$file = 'upload/filter.txt';
$searchfor = $_POST['search'];
$btn = $_POST['button'];
$sum = 0;
if($btn == 'search') {
//prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
}
?>
for example the result of the filtering will now produce 4 lines out of 1,000,000 lines from the text file
0100002291310106200140001020055460000000001000000072860103508104
0100002291320106200140001020055460000000005000000072860103508101
0100002291330106200140001020055460000000001000000072860103508102
0100002291340106200140001020055460000000005000000072860103508109
i need a code that will select only particular column and add them together using PHP code... example i only want to add columns 1-10 so the structure will look like this from the lines given above
sructure:
0100002291
0100002291
0100002291
Please Help

Related

Get specific data from txt file

I have txt file and I need to echo specific data in a loop.
Let's say my txt file name is this: myfile.txt
and the structure inside is like this:
etc="Orange" src="stack1"
etc="Blue" src="stack2"
etc="Green" src="stack3"
etc="Red" src="stack4"
How can I echo in PHP these values: Orange, Blue, Green, Red?
you can use preg_match_all for this:
<?php
# get your text
$txt = file_get_contents('your_text_file.txt');
# match against etc="" (gets val inside the quotes)
preg_match_all('/etc="([^"]+)"/', $txt, $matches);
# actual values = $matches[1]
$values = $matches[1];
echo '<pre>'. print_r($values, 1) .'</pre>';
$content = file_get_content("/path/to/myfile.txt", "r");
if (false === $content) {
// handle error if file can't be open or find
}
preg_match_all('/etc="(.*?)"/', $content, $matches);
echo implode($matches[1], ',');
With file_get_content you retrieve what's int he file.
After that you need to check if file_get_content has returned an error code (false in this case).
preg_match_all will use RegExp to filter out only what you need. In particular:
/ #is a delimiter needed
etc=" #will match literally the letters etc="
(.*?) #is a capturing group needed to collect all the values inside the "" part of etc value. So, capturing group is done with (). .* will match every character and ? make the quantifier "non greedy".
/ #is the ending delimiter
All matches are collected inside $matches array (is not necessary that $matches is previously defined.
Finally, you need to transform the collected values into a string and you can do this with implode function.
I exaplain all on code //comments.
<?php
$fichero = file_get_contents('./myfile.txt', false);
if($fichero === false){ //if file_get_contents() return false, the file isn't found, if its found, return data.
echo "Can't find file.\n";
}else{ //If file is find, this condition is executed.
$output = array(); //this variable is who will get the output of regular expression pattern from next line function.
preg_match_all('/([A-Z])\w+/',$fichero, $output);
for($i = 0; $i < count($output[0]); $i++){ //Iterate throught the first array inside of array of $output, count(array) is for get length of array.
echo $output[0][$i]; //Print values from array $output[0][$i]
if($i + 1 != count($output[0])){ //if not equal to length of array, add , at end of printed value of output[0][$i]
echo ', ';
}else{ //if equal to length of array, add . at end of printed value of $output[0][$i]
echo '.';
}
}
}
?>

Get the text just after the first ':'

In a txt file, there's the following:
Field1:Field2:Field3:Field4
Data1:Data2:Data3:Data4
How to get the text which is just after "Field1" which is "Field2" and without getting the ":" which is before "Field3" using PHP ?
NOTICE: "Field" won't be a constant string.
EDIT: I want to do something like searching for "Field2" and doing that on it's line only. So I don't want to do that for "Data" too !
Thanks.
EDIT: The main goal I wanted to ask this question for is:
IGNORE IF YOU WANT THE ANSWER, THE ANSWER IS BELOW:
I'm developing an AdminCP for my project, and if the administrator typed "User1" in a HTML form in the AdminCP it must return "This user is suspended!" if the line in the txt file was "User1:suspended:24/01/2012" .
While the format of users in the txt file is:
USERNAME:STATUS:REGISTRATION DATE
User1:suspended:24/01/2012
(All the texts and strings are just examples).
So in the below answer ... $searchfor = 'Field2'; must be $searchfor = $_POST['username']; for example.
And I wanted to use:
if( $data[1]=="suspended" ) {
echo "The user which owns ".$data[0]." is suspended!";
}
While $data[0] is the username (User1), and $data[1] is the status (suspended).
Thanks to #MagnusEriksson and PHP to search within txt file and echo the whole line . I just discovered the solution by myself:
<?php
$file = 'test.txt';
$searchfor = 'Field2';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
preg_match_all($pattern, $contents, $matches);
$wholeLine = implode("\n", $matches[0]);
$data = explode(":", $wholeLine);
echo $data[0]; // Field1
echo $data[1]; // Field2
?>

In PHP, if I find a word in a file, can I make the line that the word came from into a $string

I want to find a word in a large list file.
Then, if and when that word is found, take the whole line of the list file that the word was found in?
so far I have not seen any PHP string functions to do this
Use a line-delimited regular expression to find the word, then your match will contain the whole line.
Something like:
preg_match('^.*WORD.*$, $filecontents, $matches);
Then $matches will have the full lines of the places it found WORD
You could use preg_match:
$arr = array();
preg_match("/^.*yourSearch.*$/", $fileContents, $arr);
$arr will then contain the matches.
$path = "/path/to/wordlist.txt";
$word = "Word";
$handle = fopen($path,'r');
$currentline = 1; //in case you want to know which line you got it from
while(!feof($handle))
{
$line = fgets($handle);
if(strpos($line,$word))
{
$lines[$currentline] = $line;
}
$currentline++;
}
fclose($handle);
If you want to only find a single line where the word occurs, then instead of saving it to an array, save it somewhere and just break after the match is made.
This should work quickly on files of any size (using file() on large files probably isn't good)
Try this one:
$searhString = "search";
$result = preg_grep("/^.*{$searhString}.*$/", file('/path/to/your/file.txt'));
print_r($result);
Explanation:
file() will read your file and produces array of lines
preg_grep() will return array element in which matching pattern is found
$result is the resulting array.

preg_match exact word and print out the entire line the result was found in

i'm having a hard time understanding how to do this.
I want to search for a word, and then I want the search to return the word along with all the contents on the line the word was found in.
The word needs to be case sensitive so searching for TOM will not return Tom along with the results.
this is what I have tried thus far.
$contents = file_get_contents($file);
$pattern = preg_quote($word, '/');
$numInt = 0;
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches))
{
$numInt = count($matches[0]);
}
When I run this through my function it returns the results I want, but I noticed that it isn't consistant across different keyword.
In my text file for testing I have INT (x18) and my function returns 18 as the count. But if I use the keyword MORNING (x29) the function returns 31 which is technically correct because there are 2 instances where morning is used.
Well you could avoid using regex all together for this task.
Here's some code I whipped up:
<?php
$contents = file_get_contents($file);
#standardise those line endings
$contents = str_replace(array("\r","\r\n","\n\r","\n"),"\n",$contents);
$lines = explode("\n", $contents);
#find your result
$result = $line_num = array();
foreach($lines as $line_num => $l)
if(strpos($l, $word)) {
$result[] = $l;
$line_nums[] = $line_num;
}
echo "<pre>";
print_r($result);
echo "<br>Count:".count($result);

Can I use regex for this?

Is this possible with regex?
I have a file, and if a '#' is found in the file, the text after the '#' with the '#' is to be replaced with the file with the same name as after the '#'.
File1: "this text is found in file1"
File2: "this file will contain text from file1: #file1".
File2 after regex: "this file will contain text from file1: this text is found in file1".
I wish to do this with php and I've heard that the preg function is better than the ereg, but whatever works is fine with me =)
Thanks a lot!
EDIT:
It has to be programmed, so that it looks through file2 without knowing which files to concatenate before it has gone through all occurrences of a # :)
PHP's native functions str_pos and str_replace are better to use when you're searching through larger files or strings. ;)
First of all the grammar of your templating is not a very good one becuase the parser may not exactly sure when will the file name ends.
My suggestion would be that you change to the one that can better detect the boundry like {#:filename}.
Anyhow, the code I give below follows your question.
<?php
// RegEx Utility functions -------------------------------------------------------------------------
function ReplaceAll($RegEx, $Processor, $Text) {
// Make sure the processor can be called
if(!is_callable($Processor))
throw new Exception("\"$Processor\" is not a callable.");
// Do the Match
preg_match_all($RegEx, $Text, $Matches, PREG_OFFSET_CAPTURE + PREG_SET_ORDER);
// Do the replacment
$NewText = "";
$MatchCount = count($Matches);
$PrevOffset = 0;
for($i = 0; $i < $MatchCount; $i++) {
// Get each match and the full match information
$EachMatch = $Matches[$i];
$FullMatch = is_array($EachMatch) ? $EachMatch[0] : $EachMatch;
// Full match is each match if no grouping is used in the regex
// Full match is the first element of each match if grouping is used in the regex.
$MatchOffset = $FullMatch[1];
$MatchText = $FullMatch[0];
$MatchTextLength = strlen($MatchText);
$NextOffset = $MatchOffset + $MatchTextLength;
// Append the non-match and the replace of the match
$NewText .= substr($Text, $PrevOffset, $MatchOffset - $PrevOffset);
$NewText .= $Processor($EachMatch);
// The next prev-offset
$PrevOffset = $NextOffset;
}
// Append the rest of the text
$NewText .= substr($Text, $PrevOffset);
return $NewText;
}
function GetGroupMatchText($Match, $Index) {
if(!is_array($Match))
return $Match[0];
$Match = $Match[$Index];
return $Match[0];
}
// Replacing by file content -----------------------------------------------------------------------
$RegEx_FileNameInText = "/#([a-zA-Z0-9]+)/"; // Group #1 is the file name
$ReplaceFunction_ByFileName = "ReplaceByFileContent";
function ReplaceByFileContent($Match) {
$FileName = GetGroupMatchText($Match, 1); // Group # is the gile name
// $FileContent = get_file_content($FileName); // Get the content of the file
$FileContent = "{# content of: $FileName}"; // Dummy content for testing
return $FileContent; // Returns the replacement
}
// Main --------------------------------------------------------------------------------------------
$Text = " === #file1 ~ #file2 === ";
echo ReplaceAll($RegEx_FileNameInText, $ReplaceFunction_ByFileName, $Text);
This will returns === {# content of: file1} ~ {# content of: file2} ===.
The program will replace all the regex match with the replacement returned from the result of the given function name.
In this case, the callback function is ReplaceByFileContent in which the file name is extract from the group #1 in the regex.
I believe my code is self documented but if you have any question, you can ask me.
Hope I helps.
Much cleaner:
<?php
$content = file_get_content('content.txt');
$m = array();
preg_match_all('`#([^\s]*)(\s|\Z)`ism', $content, $m, PREG_SET_ORDER);
foreach($m as $match){
$innerContent = file_get_contents($match[1]);
$content = str_replace('#'.$match[1], $innerContent, $content);
}
// done!
?>
regex tested with: http://www.spaweditor.com/scripts/regex/index.php

Categories