Monday 3 September 2018

How to divide the file name into a table (key => value) in php?

I have a generator that create PDF files like this:

and upload files into ./files/ folder on server.
I used below code to get array:
<?php
$files = glob('files/*.{PDF,pdf}', GLOB_BRACE);
print_r($files);

OutPut:
Array
(
    [0] => files/035146-761326.PDF
    [1] => files/035150-710753.PDF
    [2] => files/035151-771208.PDF
    [3] => files/035153-718443.PDF
    [4] => files/035158-219299.PDF
    [5] => files/035159-667486.PDF
    [6] => files/035172-113022.PDF
    [7] => files/035180-482460.PDF
    [8] => files/035216-232840.PDF
)

now I wanna splite each file name to user and password. for example if i have file like this:
035180-482460.PDF
I should have:
file['user] = 035180;
file['password'] = 482460;

I know, I show foreach (files as key => value) and some stuff to split filename; but I don't know how can I do that? :(

You can use list and explode:
<?php
foreach ($files as $file) {
    $base = basename($file);
    list ($user, $pass) = explode('-', substr($base, 0, strpos($base, '.')));
    // $user would contain 035146
    // $pass would contain 761326
}

First you get the basename (convert files/035146-761326.PDF to 035146-761326.PDF) then you'd use substr and strpos to only return the file name excluding the extension, then explode using - and you get the two parts.

0 comments:

Post a Comment