Mohsen Rasouli Mohsen Rasouli - 1 year ago 74
PHP Question

How to split filename into array( key => value ) in php?

I have a generator that create PDF files like this:

enter image description here

and upload files into

folder on server.

I used below code to get array:

$files = glob('files/*.{PDF,pdf}', GLOB_BRACE);


[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
. for example if i have file like this:

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? :(

Answer Source

You can use list and explode:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download