简体   繁体   中英

PHP Regex to remove everything but the date from filename

I have a filename with a date in it, the date is always at the end of the filename. And there is no extension (because of the basename function i use).

What i have:

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

Im really not good at regex, so could someone help me with getting the date out of the filename.

Thanks

I suggest to use preg_match instead of 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'

I suggest you to try:

$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

Shorten it:

$exploded = explode( "_" , str_replace( ".txt", "", $filename ) );
echo $exploded[1];

If there is always an underscore before the date:

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))));

This should help i think:

<?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_

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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