Zack
Zack

Reputation: 1703

PHP Regex match file or directory

Given a URL path, I am attempting to create a regular expression to match if the path points to a directory, and to not match if it points to file extensions .php, .js, .html, .htm, etc.

Match:

/www/site/path/ny/

Match:

/www/news/state.208/ii

Do not match:

/www/news/index.php

Do not match:

/www/site/fr/post.py

Here is my regex that I've been working with:

^([a-zA-Z0-9/_\-]*[^/])$

This regex does what I want, but it isn't precise enough. It assumes it is a path to a file and stops matching whenever it comes across a ".", but I need to consider the possibility that the directory name contains a ".", like in the example above.

I also tried using negative look behinds with no luck:

^(.(?!\.php)|(?!\.htm?l)|(?!\.js))$

Upvotes: 0

Views: 4016

Answers (3)

Julien May
Julien May

Reputation: 2051

try this tiny one:

^.*/[^\.]*$

edit:

^.*/((?!\.js|\.php|\.html).)*$

replace or extend with the extensions you want to ignore.

Upvotes: 2

Peter Adrian
Peter Adrian

Reputation: 297

To simplify your question, you are looking for a string starting with /, and the last segment doesn't have a extension:

[\/]{0,1}.*\/[^\.]*.{1}$

Edit:

This works for all your examples:

^(.*\/){0,1}[^\.]*.{1}$

Upvotes: 1

Aleph
Aleph

Reputation: 1219

Since you're using PHP, you might want to try pathinfo instead:

$parts = pathinfo('/www/site/path/file.php');

In this case $parts['extension'] will exist, in other cases it will not.

Upvotes: 2

Related Questions