如何在 php 中将文件名拆分为数组(键 => 值)?

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

我有一个像这样创建 PDF 文件的生成器:

并将文件上传到服务器上的 ./files/ 文件夹。

我使用以下代码获取数组:

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

输出:

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
)

现在我想将每个文件名拆分为 userpassword。例如,如果我有这样的文件:
035180-482460.PDF
我应该有:

file['user] = 035180;
file['password'] = 482460;

我知道,我展示了 foreach (files as key => value) 和一些拆分文件名的东西;但我不知道我该怎么做? :(

您可以使用 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
}

首先你得到 basename (convert files/035146-761326.PDF to 035146-761326.PDF) then you'd use substr and strpos 只有 return 不包括扩展名的文件名,然后使用 - 展开并得到两个部分。

尝试:

<?php 
$files = glob('files/*.{PDF,pdf}', GLOB_BRACE);
print_r($files);
foreach($files as $file) { 
   $file = preg_replace('/\/(?=.*\/)/', ' ',  $file); // it will solve the ./files/ issue which you mentioned in comment
   //  suppose $file is files/035146-761326.PDF
   $arr = explode("/",$file); // it will give array( [0]=>files and [1]=> 035146-761326.PDF)
   $filename = explode(".",$arr[1]); // now split $arr[1] with dot, so will give new array array([0] => "035146-761326", [1] => "pdf")
   $arrname = explode("-",$filename[0]); // now split $filename[0] with - so it will give array ([0]=>035146 , [1] =>761326 )
   echo "username: ".$arrname[0];
   echo "password: ".$arrname[1];
}

?>

array_map 在这种情况下非常有用:

$files = array_map(function($name){
  preg_match('#(\d+)-(\d+)#', $name, $matches); //get user and password
  return array(
    'name' => $name,
    'user' => $matches[1],
    'password' => $matches[2]
  );
}, $files);

print_r($files);