Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP正则表达式从文件名中删除除日期以外的所有内容_Php_Regex_Date_Preg Replace - Fatal编程技术网

PHP正则表达式从文件名中删除除日期以外的所有内容

PHP正则表达式从文件名中删除除日期以外的所有内容,php,regex,date,preg-replace,Php,Regex,Date,Preg Replace,我有一个带有日期的文件名,日期总是在文件名的末尾。 并且没有扩展(因为我使用的是basename函数) 我所拥有的: $file = '../file_2012-01-02.txt'; $file = basename('$file', '.txt'); $date = preg_replace('PATTERN', '', $file); 我真的不擅长正则表达式,所以有人能帮我从文件名中去掉日期吗 谢谢我建议您试试: $exploded = explode("_", $filename);

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

我所拥有的:

$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);
我真的不擅长正则表达式,所以有人能帮我从文件名中去掉日期吗

谢谢

我建议您试试:

$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

如果日期前始终有下划线:

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_

?>

我建议使用preg\u match而不是preg\u 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'

当你说“约会出去”时,你的意思是移除还是取回?啊,太好了,完全没有想到这一点。现在觉得有点愚蠢:)非常感谢。或者
$date=end(explode(''uu',str_replace('.txt','','$filename))这实际上就是我要找的,这样一来,他们在日期前放了什么并不重要。谢谢
$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'