0

我有一个带有日期的文件名,日期总是在文件名的末尾。并且没有扩展名(因为我使用了 basename 函数)。

是)我有的:

$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);

我真的不擅长正则表达式,所以有人可以帮我从文件名中取出日期。

谢谢

4

5 回答 5

1

我建议使用 preg_match 而不是 preg_replace:

$file = '../file_2012-01-02';
preg_match("/.*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/", $file, $matches);
echo $matches[1]; // contains '2012-01-02'
于 2012-09-24T14:41:03.783 回答
0

我建议你尝试:

$exploded = explode("_", $filename);
echo $exploded[1] . '<br />'; //prints out 2012-01-02.txt
$exploded_again = explode(".", $exploded[1]);
echo $exploded_again[0]; //prints out 2012-01-02

缩短它:

$exploded = explode( "_" , str_replace( ".txt", "", $filename ) );
echo $exploded[1];
于 2012-09-24T14:31:47.850 回答
0

如果日期前总是有下划线:

ltrim(strrchr($file, '_'), '_');
      ^^^^^^^ get the last underscore of the string and the rest of the string after it
^^^^^ remove the underscore
于 2012-09-24T14:35:27.607 回答
0

有了这个,当你真的需要时使用正则表达式:

current(explode('.', end(explode('_', $filename))));
于 2012-09-24T14:37:41.973 回答
0

这应该有助于我思考:

<?php

$file = '../file_2012-01-02.txt';
$file = basename("$file", '.txt');
$date = preg_replace('/(\d{4})-(\d{2})-(\d{2})$/', '', $file);

echo $date; // will output: file_

?>
于 2012-09-24T14:37:55.560 回答