preg_grep无法使用有效的正则表达式进行捕获

时间:2014-02-13 19:18:28

标签: php regex

给出表格中的字符串数组

$log_files = Array("access_log.201401231215.txt", 
                   "access_log.201401231230.txt", 
                   "old_format_access_log.201401231200.txt");

我想将所有给定格式的字符串(例如"access_log.*TIMESTAMP*.txt")放入数组中,但preg_grep不起作用。

$file_format_to_capture = "access_log"

$re = "^" . $file_format_to_capture  . ".*?$";

$matched_files = preg_grep($re, $log_files);

在我的netbeans控制台中,我可以看到$re设置为"^access_log.*?$"which seems correct。我希望捕获$log_files数组的前两个元素。

2 个答案:

答案 0 :(得分:3)

您需要add delimiters

$re = "/^" . $file_format_to_capture  . ".*?$/";

您还可以在PHP中使用~regex~#regex#

答案 1 :(得分:2)

正则表达式需要分隔符。我个人喜欢使用括号,因为它们是匹配的对(因此它们不需要转义模式中的任何东西“只是因为它是相同的符号),它也可以作为索引{{1}的提醒匹配对应于整个匹配。

所以:

0

我还使用preg_quote来涵盖您的文件格式可能具有重要字符的边缘情况(最值得注意的是$re = "(^".preg_quote($file_format_to_capture).")"; ),并且.是不必要的,因此我将其删除