Click here to Skip to main content
15,354,574 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The filename is files_in_dir.php
In the working directory there is a folder. That name is files_test .
In that folder there are two text file:

file1.txt contains:

AAAAAAAA
BBBBBBBB
CCCCCCCC
DDDDDDDD

file2.txt contains:

AAAAAAAA
BBBBBBBB
DDDDDDDD
CCCCCCCC

We are searching for "CCCCCCCC" pattern and want to know its line number and echo $line_number of each file. That's all!

What I have tried:

PHP
<?php
//CURRENT FILE NAME IS: files_in_dir.php
//My working directory: /home/Zoltan/Dokumentumok
$files = array_diff(scandir("files_test"), array('..', '.'));
//Files scanned into $files from files_test folder

echo getcwd()."\n";

echo "THINGS IN WORKING DIRECTORY";
//Files and folder listed in working directory
foreach (scandir('.') as $file)
    echo $file . "\n";
    
echo "\n";

//Now I would like to find which line is in the CCCCCCCC pattern in each file in files_test directory
foreach($files as $file) {
  echo $file."\n";
  $search      = "CCCCCCCC";
//BUT THE NEXT LINE DOES NOT WORK
  $lines       = file($file);
  $line_number = false;
  
  while (list($key, $line) = each($lines) and !$line_number) {
   $line_number = (strpos($line, $search) !== FALSE) ? $key + 1 : $line_number;
  }
//And print the line number
  echo "The line number is: ".$line_number."\n";

}
?>
Posted
Updated 18-May-22 1:26am
v2

1 solution

PHP
$lines       = file('"'.$file.'"');

Why are you adding the quote characters around the file name? Just use the simple variable as described at PHP: file - Manual[^].
   
Comments
folza 18-May-22 7:42am
   
I did that but got the following warning:

PHP Warning: file(file1.txt): failed to open stream: No such file or directory in /home/Zoltan/Dokumentumok/files_in_dir.php on line 21
Richard MacCutchan 18-May-22 9:39am
   
Well that message is quite clear, the system cannot find a file with that name. You need to make sure that you provide the full path to the file's location.
folza 18-May-22 11:29am
   
Yes, that was the solution. It needs an absolute path like this:

$lines = "/home/Zoltan/Dokumentumok/files_test/".$file;

THX!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900