Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 364
  • Last Modified:

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?
0
itamar
Asked:
itamar
  • 2
  • 2
1 Solution
 
ThGCommented:

function CheckPattern($filename, $prefix, $ext) {
 $testExp = "/^".$prefix."([\.\+\-\@\w\d])*\.".$ext."$/";
 return preg_match($testExp, $filename);
}

this is your fixed function *BUT* it's very bad coding, because regexp have many metacharacters, so inserting a raw parameter into the regular expression might cause unexpected behaviour.
Guess what would happen if you enforce suffix:
".jpg"
that would match "Ajpg", "5jpg", "?jpg"
0
 
itamarAuthor Commented:
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
0
 
itamarAuthor Commented:
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
0
 
ThGCommented:

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.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now