简体   繁体   English

正则表达式匹配文件名中的字符串

[英]Regex to match character string in filename

I am trying to make a list of all PHP files within a directory that have a specific character string (in my case a datestamp) at the beginning of the name AND a specific string ".php" at the end. 我正在尝试列出目录中所有PHP文件的列表,这些文件在名称的开头有一个特定的字符串(在我的例子中是一个日期戳),最后是一个特定的字符串“.php”。 My date is being passed in as a variable ($SearchDate). 我的日期作为变量传递($ SearchDate)。 I have already successfully set up the PHP script to read in a full list of files from my directory, and was just trying to use preg_match to filter the list for me. 我已成功设置PHP脚本以从我的目录中读取完整的文件列表,并且只是尝试使用preg_match来为我过滤列表。 Unfortunatly I am a complete failure at RegEx even having tried repeatedly with this cheatsheet . 不幸的是,即使我已经多次尝试使用这张备忘单,我在RegEx完全失败了。

Here is what I have that is generating errors and no results: 以下是我所产生的错误,没有结果:

$SearchDate = '2013-02'; //example for february of 2013

if(preg_match('#^('.$SearchDate.')+[:graph:]{1}(\.(pdf))#', $file)) {
   //do something
}

I also tried: 我也尝试过:

preg_match('#^\Q'.$SearchDate.'\E+[:graph:]{1}\Q.pdf\E#', $file)

My filenames look like this: 我的文件名看起来像这样:

2013-02-fileNameMightBeAlphaOr1234567890.pdf 2013-02-fileNameMightBeAlphaOr1234567890.pdf

The errors I am getting look like this: 我得到的错误看起来像这样:

Warning: preg_match() [function.preg-match]: Compilation failed: POSIX named classes are supported only within a class at offset 5 in /home/directory/myfile.php on line 26 警告:preg_match()[function.preg-match]:编译失败:仅在第26行/home/directory/myfile.php中偏移量为5的类中支持POSIX命名类

I need to also be checking that it ends with ".pdf" so I basically need the start and end of the filename and don't care what happens in the middle. 我还需要检查它以“.pdf”结尾,所以我基本上需要文件名的开头和结尾,而不关心中间发生了什么。

If that's the case then following regex should work for you: 如果是这种情况,那么跟随正则表达式应该适合你:

if(preg_match('#^' . $SearchDate . '.*?\.pdf$#', $file)) {
   //do something
}

Live Demo: http://ideone.com/h66GY0 现场演示: http//ideone.com/h66GY0

这个简单的正则表达式应该可行

preg_match('/^'.$SearchDate.'/', $file);

{}添加到图表中......就像

     preg_match('#^('.$SearchDate.')+[{:graph:}]{1}(\.(pdf))#', $file)

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

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