3

I have this regex:

'/^files\/(.+\..+)$/';

But I want to replace the "files/" section with a runtime variable.

I tried this:

$filePath = "files/";
'/^'.$filePath.'(.+\..+)$/';

which didn't work, as well as this:

$filePath = preg_quote("files/");
'/^'.$filePath.'(.+\..+)$/';

but I still get an error in this loop on the preg_match line, saying that "(" is an unknown modifier.

foreach (glob(FILE_PATH."*.*") as $filename) {
    preg_match($pattern, $filename, $matches);
    echo "<option class='file' value='".$matches[1]."'>".$matches[1]."</option>";
}

Any help would be appreciated, thanks.

EDIT

This works...

$filePath = 'files\/';

...but in actual usage, I'm trying to use a constant declared in another file.

So:

define('FILE_PATH', 'files/');

...and then trying to use that constant. It can't have the escape character embedded because some other parts of the application need it without the escape character.

2
  • Does $filePath contain slashes (/)? That conflicts with the regex delimiters you use. You should always regex-escape content you inject into expressions. Commented Nov 25, 2012 at 14:46
  • @arkascha he does (that's what preg_quote is for). he is just missing a parameter ;) Commented Nov 25, 2012 at 14:48

1 Answer 1

3

You need to hand preg_quote the delimiter:

$filePath = preg_quote("files/", '/');

Since you can use a lot of characters as delimiters, preg_quote cannot know, that you are going to use /, so it does not escape it by default. That's what the second (optional) parameter is for.

Otherwise, your second approach (the one using preg_quote) is the way to go.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Don't know how I missed that, thank you very much! Will accept the answer as soon as it lets me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.