我有一个带有日期的文件名,日期总是在文件名的末尾。并且没有扩展名(因为我使用了 basename 函数)。
是)我有的:
$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);
我真的不擅长正则表达式,所以有人可以帮我从文件名中取出日期。
谢谢
我有一个带有日期的文件名,日期总是在文件名的末尾。并且没有扩展名(因为我使用了 basename 函数)。
是)我有的:
$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);
我真的不擅长正则表达式,所以有人可以帮我从文件名中取出日期。
谢谢
我建议使用 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'
我建议你尝试:
$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];
如果日期前总是有下划线:
ltrim(strrchr($file, '_'), '_');
^^^^^^^ get the last underscore of the string and the rest of the string after it
^^^^^ remove the underscore
有了这个,当你真的需要时使用正则表达式:
current(explode('.', end(explode('_', $filename))));
这应该有助于我思考:
<?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_
?>