简体   繁体   中英

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))$

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.

try this tiny one:

^.*/[^\.]*$

edit:

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

replace or extend with the extensions you want to ignore.

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}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM