I have a function that retrieves file names in some directory. The directory has multiple PDF files.
I want to assign a key to each of the PDF files I gathered, where the key is the number that is located between -
and .pdf
in the filename.
For instance I have 3 PDF files:
abc-1.pdf
abc-2.pdf
abc-3.pdf
What I want to have:
1 => abc-1.pdf,
2 => abc-2.pdf,
3 => abc-3.pdf
My function is currently this:
function getPDFs($PDF_DIR_NAME, $PDF_TOKEN) {
if ($PDF_TOKEN == null || $PDF_TOKEN == '') {
return null;
} else {
$getPDFVersions = $PDF_TOKEN.
"*";
$dirs = glob($PDF_DIR_NAME.
'/'.$getPDFVersions);
$files = array();
foreach($dirs as $d) {
if (filesize($d) > 200) {
$files[] = basename($d);
}
}
return $files;
}
}
How can I assign keys for each PDF document?
Ingredients:
strrchr()
: Find the last occurrence of a character in a stringsubstr()
: Return part of a string(int)
- Cast to integer (if required)Recipe:
-
), as it comes before the ID..
), as it comes after the ID (see below)substr()
and the information gathered in step 1 (and 2) Optionally, use the IDs to populate an associative array, like so:
$myPDFs = array();
$myPDFs[$id] = $filename;
Or whatever it is you need.
PS:
Instead of finding the position of the last dot, you could also simply assume that it is always 4 characters before the end of the filename. Seems a safe bet. Hint: substr()
can take a negative number as its start
parameter.