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])*\.".$e xt."$";
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?
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\
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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.
ASKER
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