繁体   English   中英

PHP Regex从文件名中删除除日期以外的所有内容

[英]PHP Regex to remove everything but the date from filename

我有一个带日期的文件名,日期始终在文件名的末尾。 而且没有扩展名(因为我使用的是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

这样,当您确实需要使用regexp时:

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_

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM