1252748
1252748

Reputation: 15369

preg_grep failing to capture with a valid regex

Given the array of strings in the form

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

I want to put into an array all of the strings that are in a given format (eg, "access_log.*TIMESTAMP*.txt") but the preg_grep is not working.

$file_format_to_capture = "access_log"

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

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

In my netbeans console I can see $re is set to "^access_log.*?$", which seems correct. I would expect to capture the first two elements of the $log_files array.

Upvotes: 0

Views: 106

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324780

Regexes need delimiters. Personally I like to use parentheses, because they come in matching pairs (therefore they don't require anything in the pattern to be escaped "just because" it's the same symbol), and it also serves as a reminder that index 0 of matches corresponds to the whole match.

So:

$re = "(^".preg_quote($file_format_to_capture).")";

I've also used preg_quote to cover edge cases where you might have a significant character in your file format (most notably .), and .*?$ is unnecessary so I removed it.

Upvotes: 2

Sam
Sam

Reputation: 20486

You need to add delimiters:

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

You can also use ~regex~ or #regex# in PHP.

Upvotes: 3

Related Questions