Link to home
Start Free TrialLog in
Avatar of itamar
itamar

asked on

Filtering files with regular expression

I'm trying to filter files in a directory.
To do so, I need a function using regular expression that can accept 3 parameters:
a filename, a prefix and an extension and returns true (match) or false (no match)

My code at this moment is:

<?php
function CheckPattern($filename, $prefix, $ext) {
  $testExp = "^".$prefix."([\.\+\-\@\w\d])*\.".$ext."$";
  return ($testExp, $filename) );
}
$sPref = "ABC";
$sExt = "xml";
$file = "ABC-123asq.xml";
 if (CheckPattern($file, $sPref, $sExt)) {
     echo "Its a match";
 } else {
     echo "No match";
 }
?>

It should return a match in this example, but it doesn't :-(
I'm stucked on this.

Any help?
ASKER CERTIFIED SOLUTION
Avatar of Giovanni G
Giovanni G
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of itamar
itamar

ASKER

Hi ThG,

I got your point.
But it is part of a bigger context.
Extensions are choosen from a list and prefix probably will be letters from A to Z (index)

Many thanks.

Itamar
Avatar of itamar

ASKER

Hi again,

looking at your code I could see the difference is in "/^" and "$/"

As I'm PHP beginner could you explain why it's necessary as a bonus ;-))

Thanks again

OK :-)
That's not php related, that's the basic syntax for regular expressions. A regular expression is anclosed between two delimiters, no matter which they are, but you SHOULD use "/"
you were probably getting an error related to missing delimiter "^", because it thought you were using "^" and "^" as delimiters, which is totally wrong.