views:

144

answers:

1

Can someone please help me with this preg_match

if (preg_match('~[^A-Za-z0-9_\./\]~', $filepath))
    // Show Error message.

I need to match a possible filepath. So I need to check for double slashes, etc. Valid file path strings should look like this only:

mydir/aFile.php

or

mydir/another_dir/anyfile.js

So a slash at the beginning of this string should be checked also. Please help.

Thanks :)

EDIT: Also, guys, this path is being read from within a text file. It is not a filepath on the system. So hopefully it should be able to support all systems in this case.

RE-EDIT: Sorry, but the string can also look like this too: myfile.php, or myfile.js, or myfile.anything

How do I allow strings like this as well?? I apologize for not being too specific on this before...

+4  A: 

You can do:

if(preg_match('#^(\w+/){1,2}\w+\.\w+$#',$path)) {
        // valid path.
}else{
        // invalid path
}
codaddict
can I use this like so to only check for invalid paths only? `if(!preg_match('#^(\w+/){1,2}\w+\.\w+$#',$path))`
SoLoGHoST
Yeah you can do that.
codaddict
Sorry, this isn't working, I tried it, but it's going to an error message when I have this string: `myfile.php`
SoLoGHoST
Ok, it doesn't have to have a slash in it, how do I change this to account for that as well??
SoLoGHoST
preg_match('#^(\w+/){0,2}\w+\.\w+$#',$path)
MartyIX
ok, so here's what I'm using `if (!preg_match('#^(\w+/){1,2}\w+\.\w+$#', $filepath))`, how can allow paths like this: `afile.php` without any slashes and still keep it restricted like you have it?Thanks again, and sorry for the inconvenience.
SoLoGHoST
http://www.webcheatsheet.com/php/regular_expressions.php - check a tutorial on regular expressions.
MartyIX
Thank You Very much MartyIX :)
SoLoGHoST
Ok, will do, and Cheers :)
SoLoGHoST
Wow, that's a good tutorial also, explains it very well. Thanks!
SoLoGHoST