【问题标题】:How to split filename into array( key => value ) in php?如何在php中将文件名拆分为数组(键=>值)?
【发布时间】:2016-10-17 18:52:19
【问题描述】:

我有一个生成器,可以像这样创建 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 =&gt; value) 和一些东西来分割文件名;但我不知道我该怎么做? :(

【问题讨论】:

  • 你应该至少提供你尝试过的东西!

标签: php arrays string foreach explode


【解决方案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);

【讨论】:

  • 非常好的 php 匿名函数示例!
  • 很高兴听到这个消息:)
【解决方案2】:

您可以使用listexplode

<?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(将files/035146-761326.PDF转换为035146-761326.PDF)然后你会使用substrstrpos只返回不包括扩展名的文件名,然后使用-分解你得到这两个部分。

【讨论】:

  • files/035146-761326.PDF 有另一个问题。
  • 如何删除files/
  • Basename 返回的文件名不包括任何路径,因此它将删除它
【解决方案3】:

试试:

<?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];
}

?>

【讨论】:

  • 我有另一个问题files/035146-761326.PDF 如何删除./files/
猜你喜欢
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2018-10-03
  • 1970-01-01
  • 2013-08-29
相关资源
最近更新 更多