[英]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.