So I was wondering how to detect the right files, by their names, when I scan through them.
Right now when I open a pop-up window, I GET
a id (?id=2451961
), and this id is used to detect image
files in a folder. But how should i detect them?
Is there a way to say, the start of the files name to the first non-number should be the id, and if it’s equal to the id then thats one of the files?
The folder with some files could be this:
Right now I loop through the files like this, but it doesn’t get the file '2451961 - Copy.png'
:
foreach ($list as $file) { $file_name = strtolower(substr(strtok($file, '.'),0)); $type = strtolower(substr(strrchr($file,"."),1)); if ($type != "log" ) { if ((strtok($file, '_') == $id) || $file_name == $id) { $scr = '../test/ftp_image.php?img='.$file; ?> <img src="<?php echo $scr; ?>" height="250px"/> <?php echo $file; } } }
Note: there is a statement exclude = .log files
in the code, which is because there is some files containing text which shouldn’t be takes into consideration.
The files i want to get in this example is these:
NOTE: Not all images will be .png, there could be a .jpg or something like that.
file names:
2451961 - Copy.png 2451961.jpg 2451961 - Copy 2.png 2451961 - Copy_2.jpeg
Advertisement
Answer
Regex looks like a better/right tool for this job. Your regex could look like below:
'/^'.preg_quote($id).'D/'
preg_quote
is just for escaping of any regex metacharacters. So, your file name should start with the ID followed by a non digit, which is D
. We won’t have to care about file extensions if we do it this way.
Snippet:
<?php $files = [ '2451961 - Copy.png', '2451961.png', '2451961_2 - Copy.png', '2451961_2.png', '4405.png' ]; $id = '2451961'; foreach($files as $file){ echo $file, " ", var_dump(preg_match('/^'.preg_quote($id).'D/', $file) === 1),PHP_EOL; }