Extracting fulldate from yyyy-m-dd?
i've got 100s of files with names like:
CPC_2001_5_21_7.pdf
CPC_YYYY_M_DD_7.pdf
The last number is a page number and its irrel开发者_StackOverflow中文版evant. I want to sort them out into directories like:
YYYYMMDD (ie: 20010521)
You can extract the year, month and day with:
if (preg_match('/^CPC_(\d{4})_(\d{1,2})_(\d{1,2}).*$/', $filename, $matches)) {
list($file, $year, $month, $day) = $matches;
}
If I were you, I would use the heavenly DateTime::createFromFormat. This allows you to designate a pattern and create a DateTime object from it.
So, for example,
$date = 'CPC_2001_5_21_7.pdf';
$dt = DateTime::createFromFormat('!*Y_n_d_*.*', $date);
You can then build a string with the data you want:
$filename = $dt->format('Ymd') . '.pdf';
You should split by underscore, then format the new filename using nullpadding.
<?php
$filenames = array(
"CPC_2001_5_21_7.pdf",
"CPC_2002_2_13_7.pdf",
"CPC_2004_6_23_7.pdf"
);
$newfilenames = array();
foreach($filenames as $filename)
{
$split = explode("_", $filename);
$newfilenames[] = sprintf("%04s%02s%02s", $split[1], $split[2], $split[3]) . ".pdf";
}
print_r($newfilenames);
?>
outputs
Array
(
[0] => 20010521.pdf
[1] => 20020213.pdf
[2] => 20040623.pdf
)
加载中,请稍侯......
精彩评论