Reputation: 16364
I'm looking to open a file in PHP with a certain regex. Here is the example. I have two files in the same folder:
20151001_Test(132489488)_test_summary.txt
20150930_Test(132489488)_test.txt
These two files are in the same folder, the number at the beginning (20151001) is changing. But I want to find the second file, just with the first's number (132489488). Something like:
$number = preg_replace('/20151001_Test\((.*)\)_test_summary.txt/','$1',$line);
$file = file_get_content('/.*_Test(' . $number . ')_test.txt/');
Someone has the answer maybe?
Thanks a lot!
Upvotes: 1
Views: 967
Reputation: 5032
You can't use regex arguments in file_get_content()
; it requires a single fixed string filename.
If you want to search for files that match a pattern, then you first need to read the list of filenames from the directory. You would use scandir()
for this.
Then you need to search the resulting array to find the matching filenames. The PHP function for this is preg_grep()
. This is a regex function, you so can use your regex here.
Once you've found the matching filename using the above, then you can pass that filename into file_get_contents()
to load the file.
Upvotes: 1
Reputation: 6742
You need to fetch the list of filenames before finding the one to use.
Something like this
$dir = '/your/directory/here/';
$number = preg_replace('/20151001_Test\((.*)\)_test_summary.txt/','$1',$line);
$files = scandir($dir);
$matching = preg_grep('/_Test(' . $number . ')_test.txt/');
if ($matching) {
$file = file_get_content($matching[0]);
}
Upvotes: 4