It sounds very simple and it should be but I've got some issue and can't find it.
I have a file with words on each line, like
dog
dog
dog
dogfirend
dogandcat
dogcollar
dog-food
The above should display me: 3 (since there are only 3 full matches of dog)
I'm trying to read the file and check how many times the word dog is inside. The problem is that it doesn't count at all and shows 0. This is what I have
$word = "dog";
$count = 0;
$handle = fopen("dogs.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if ($word == $line) {
$count++;
}
}
fclose($handle);
}
The lines in your file are separated by a newline. This newline is included in your $line variable.
From the fgets() manual: "Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first)."
You need to trim() your $line first, so those characters get removed:
$word = "dog";
$count = 0;
$handle = fopen("dogs.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if ($word == trim($line)) {
$count++;
}
}
fclose($handle);
}
echo $count
Related
I have a question. How can i get a string from a entry in a textfile.
The texfile looks like:
Blabla2|123456
Blablablabla4|475387638
Blab1|387549900
Now i want to get from Blablablabla4 the number behind the |
Whats the read file function for it?
You can create a custom function, if you need that value often with different keys.
function getValueFromFile($file, $key){
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
if($data[0] == $key){
fclose($handle);
return $data[1];
}
}
fclose($handle);
}
return false;
}
and simply call it like:
echo getValueFromFile("your file name", "Blablablabla4");
Load each line of file to $line and then use function explode('|', $line_variable) for separating a string from int.
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = explode('|', $line);
$string = $line[0];
}
fclose($handle);
} else {
// error opening the file.
}
I'm new at PHP so I'm need help to build this script.
I have a file.txt file with following lines:
aaaa 1234
bbba 1234
aaaa 1236
cccc 1234
aaaa 1238
dddd 1234
I want to find the line with string "aaaa" and print:
String "aaaa" found 3 times at lines: 1, 3, 5.
And better it can print these lines.
I tried this code:
<?
function find_line_number_by_string($filename, $search, $case_sensitive=false ) {
$line_number = '';
if ($file_handler = fopen($filename, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search); //convert file and search string
$line = strtolower($line); //to lowercase
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number .= $i.",";
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or filename";
}
//if no match found
if(count($line_number)){
return substr($line_number, 0, -1);
}else{
return "No match found";
}
}
$output = find_line_number_by_string('file.txt', 'aaaa');
print "String(s) found in ".$output;
?>
But I dont know how to count total of strings found (3) and print each found line.
Thank in advance.
There are lots of ways to do this that produce the same final result but differ in the specifics.
Assuming that your input is not large enough that you are concerned about loading it in memory all at once, one of the most convenient approaches is to use file to read the file's contents into an array of lines, then preg_grep to filter the array and only keep the matching lines. The resulting array's keys will be line numbers and the values will be whole lines that matched, perfectly fitting your requirements.
Example:
$lines = file('file.txt');
$matches = preg_grep('/aaaa/', $lines);
echo count($matches)." matches found.\n";
foreach ($matches as $line => $contents) {
echo "Line ".($line + 1).": ".$contents."\n";
}
$str = "aaaa";
$handle = fopen("your_file.txt", "r");
if ($handle) {
echo "String '".$str."' found at lines : ";
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
echo implode(", ", $arr_lines).".";
}
UPDATE 2 :
$file = "your_file.txt";
$str = "aaaa;";
$arr = count_line_no($file, $str);
if(count($arr)>0)
{
echo "String '".$str."' found at lines : ".implode(", ", $arr).".";;
}
else
{
echo "String '".$str."' not found in file ";
}
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen("your_file.txt", "r");
if ($handle) {
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
}
return $arr_lines;
}
**Try it for solve your problam **
if(file_exists("file.txt")) // check file is exists
{
$f = fopen("file.txt", "r");
// Read line by line until end of file
$row_count = 0;
while(!feof($f))
{
$row_count += 1;
$row_data = fgets($f);
$findme = 'aaaa';
$pos = strpos($row_data, $findme);
if ($pos !== false)
{
echo "The string '$findme' was found in the string '$row_data'";
echo "<br> and line number is".$row_data;
}
else
{
echo "The string '$findme' was not found ";
}
}
fclose($f);
}
<?php
$handle = fopen("wqer.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if(preg_match("/aut/i", $line)){
**echo fgets($handle).fgets($handle);**
}
}
} else {
echo "Error loading file.";
}
?>
The textfile wqer.txt looks something like that (but it has 12k lines :D):
bike
*aut*
car
ball
mouse
*aut*
light
house
I want from this script to echo next 2 lines after finding the aut line from this file.
So the output should look like this:
car
ball
light
house
Yep sorry, house should be the last one.
Solved, many thanks to Wrikken, simple solution, I almost feel embarrased :)
$found = 0;
while (($line = fgets($handle)) !== false) {
if(preg_match("/aut/i", $line)){
$found = 2;
continue; // if you don't want "aut" to be printed. remove otherwise.
}
if ($found > 0) {
echo $line;
$found--;
}
}
Add error checking:
$lines = file("wqer.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map('trim', $lines); //in case there are spaces etc. that are not shown
foreach($lines as $key => $val) {
if($val == '*aut*') { //(stripos($val, 'aut') !== false) //to keep similar to how you have it now
echo $lines[$key+1] . "\n" . $lines[$key+2] . "\n";
}
}
I have an application which needs to open the file, then find string in it, and print a line number where is string found.
For example, file example.txt contains few hashes:
APLF2J51 1a79a4d60de6718e8e5b326e338ae533 EEQJE2YX
66b375b08fc869632935c9e6a9c7f8da O87IGF8R
c458fb5edb84c54f4dc42804622aa0c5 APLF2J51 B7TSW1ZE
1e9eea56686511e9052e6578b56ae018 EEQJE2YX
affb23b07576b88d1e9fea50719fb3b7
So, I want to PHP search for "1e9eea56686511e9052e6578b56ae018" and print out its line number, in this case 4.
Please note that there are will not be multiple hashes in file.
I found a few codes over Internet, but none seem to work.
I tried this one:
<?PHP
$string = "1e9eea56686511e9052e6578b56ae018";
$data = file_get_contents("example.txt");
$data = explode("\n", $data);
for ($line = 0; $line < count($data); $line++) {
if (strpos($data[$line], $string) >= 0) {
die("String $string found at line number: $line");
}
}
?>
It just says that string is found at line 0.... Which is not correct....
Final application is much more complex than that...
After it founds line number, it should replace string which something else, and save changes to file, then goes further processing....
Thanks in advance :)
An ultra-basic solution could be:
$search = "1e9eea56686511e9052e6578b56ae018";
$lines = file('example.txt');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key + 1 : $line_number;
}
echo $line_number;
A memory-saver version, for larger files:
$search = "1e9eea56686511e9052e6578b56ae018";
$line_number = false;
if ($handle = fopen("example.txt", "r")) {
$count = 0;
while (($line = fgets($handle, 4096)) !== FALSE and !$line_number) {
$count++;
$line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
}
fclose($handle);
}
echo $line_number;
function get_line_from_hashes($file, $find){
$file_content = file_get_contents($file);
$lines = explode("\n", $file_content);
foreach($lines as $num => $line){
$pos = strpos($line, $find);
if($pos !== false)
return $num + 1
}
return false
}
get_line_from_hashes("arquivo.txt", "asdsadas2e3xe3ceQ#E"); //return some number or false case not found.
If you need fast and universal solution that working also for finding line number of multiline text in file, use this:
$file_content = file_get_contents('example.txt');
$content_before_string = strstr($file_content, $string, true);
if (false !== $content_before_string) {
$line = count(explode(PHP_EOL, $content_before_string));
die("String $string found at line number: $line");
}
FYI Works only with PHP 5.3.0+.
$pattern = '/1e9eea56686511e9052e6578b56ae018/';
if (preg_match($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
//PREG_OFFSET_CAPTURE will add offset of the found string to the array of matches
//now get a substring of the offset length and explode it by \n
$lineNumber = count(explode("\n", substr($content, 0, $matches[0][1])));
}
If the file is not extremely large then just read the file into an array file, search for the word preg_grep, get the index key for that line and add 1 since the array starts at 0:
$string = "1e9eea56686511e9052e6578b56ae018";
echo key(preg_grep("/$string/", file("example.txt"))) + 1;
I found this to work great and be very efficient; Simply explode the file by each line and search through the array for your search terms like so:
function getLineNum($haystack, $needle){
# Our Count
$c = 1;
# Turn our file contents/haystack into an array
$hsarr = explode("\n", $haystack);
# Iterate through each value in the array as $str
foreach($hsarr as $str){
# If the current line contains our needle/hash we are looking for it
# returns the current count.
if(strstr($str, $needle)) return $c;
# If not, Keep adding one for every new line.
$c++;
}
# If nothing is found
if($c >= count($hsarr)) return 'No hash found!';
}
EDIT: Looking through the other answers, I realize that Guilherme Soares had a similar approach but used strpos, which in this case doesnt work. So I made a few alterations with his idea in mind here:
function getLineNum($haystack, $needle){
$hsarr = explode(PHP_EOL, $haystack);
foreach($hsarr as $num => $str) if(strstr($str, $needle)) return $num + 1;
return 'No hash found!';
}
Live Demo: https://ideone.com/J4ftV3
How to count specific lines in a text file depending on a particular variable in that line.
For example i need to count the lines of a text file only containing for instance $item1 or $item2 etc.
Sounds like you need something like what grep -c do in the shell, try something like this:
$item1 = 'match me';
$item2 = 'match me too';
// Thanks to #Baba for the suggestion:
$match_count = count(
preg_grep(
'/'.preg_quote($item1).'|'.preg_quote($item2).'/i',
file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
)
);
// does the same without creating a second array with the matches
$match_count = array_reduce(
file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
function($match_count, $line) use ($item1, $item2) {
return
preg_match('/'.preg_quote($item1).'|'.preg_quote($item2).'/i', $line) ?
$match_count + 1 : $match_count;
}
);
The above code sample uses the file() function to read the file into an array (splitted by lines), array_reduce() to iterate that array and preg_match() inside the iteration to see if a line matched (the /i at the end makes it case-insensitive).
You could use a foreach as well too.
This code reads file.php and counts only lines containing '$item1' or '$item2'. The check itself could be finetuned, since you have to add a new stristr() for every word you want to check.
<?php
$file = 'file.php';
$fp = fopen($file, 'r');
$size = filesize($file);
$content = fread($fp, $size);
$lines = preg_split('/\n/', $content);
$count = 0;
foreach($lines as $line) {
if(stristr($line, '$item1') || stristr($line, '$item2')) {
$count++;
}
}
echo $count;
Read your file line by line and use strpos to determine if a line contains a specific string/item.
$handle = fopen ("filename", "r");
$counter = 0;
while (!feof($handle))
{
$line = fgets($handle);
// or $item2, $item3, etc.
$pos = strpos($line, $item);
if ($pos !== false)
{
$counter++
}
}
fclose ($handle);