PHP读取文件名,并在文件名中的数字,回显标题与相应的月份


PHP read file name, and the number in file name, echo heading with corresponding month

我有一个php脚本,工作得很好,但我想回显一个标题,列出了它的月份。文件名将包含_01,_02,_03等。我已经创建了一个$months数组,但是我正在尝试找出最好的方法。

如果文件名包含_01,则回显January。否则,如果文件名包含_02,则返回二月。有人知道这个场景的最佳实践吗?

foreach (glob("*.mov") as $filename)
$theData = file_get_contents($filename) or die("Unable to retrieve file data");
$months = ['_01', '_02', '_03', '_04', '_05', '_06', '_07', '_08', '_09', '_10', '_11', '_12'];

试试这个:

foreach (glob("*.mov") as $filename)
$theData = file_get_contents($filename) or die("Unable to retrieve file data");
$months = ['January' => '_01', 'February' =>  '_02', 'March' => '_03', 'April' => '_04', 'May' => '_05', 'June' => '_06', 'July' => '_07', 'August' => '_08', 'September' => '_09', 'October' => '_10', 'November' => '_11', 'December' => '_12'];
foreach($months as $key => $month){
  if(strpos($filename,$month)!==false){
      echo $key;
  }
}

可能与此类似-基于月份数字在文件名中只会出现一次

foreach($theData as $filename){
    preg_match('/_('d{2})/', $filename, $match);
    echo date('F',strtotime($match[1].'/20/2000'));
}

这是我能想到的

$files = [
    "file_01",
    "file_02asdf",
    "file_03_sfsa",
    "file_04_23",
    "file_05 cat"
];
foreach($files as $file){
    preg_match("/_('d{2,2})/", $file, $matches);
    echo date("F", strtotime("2000-{$matches[1]}-01"))."'n";
}

的结果是:


1月2月
3月
4月
可能

也许这是另一种方式,但preg_match似乎更聪明

function getMonthnameByFilename($filename,$months) {
   foreach($months as $index => $m) {
        if(strpos($filename,$m) !== false) {
          return date("F",strtotime("2013-".($index+1)."-1"));
        }
    }
    return false;
}