Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match url without file extension

I would like some help matching the following urls.

/settings => /settings.php
/657_46hallo => /657_46hallo.php
/users/create => /users.php/create
/contact/create/user => /contact.php/create/user
/view/info.php => /view.php/info.php
/view/readme - now.txt => /view.php/readme - now.txt
/ => [NO MATCH]
/filename.php => /unknown.php
/filename.php/users/create => /unknown.php

if the first part after the domain name is a filename ending with ".php" (see last 2 examples) It should redirect to /unknown.php

I think I need 2 regular expressions 1st should be almost something like: ^/([a-zA-Z0-9_]+)(/)?(.*)?$ 2nd to catch the direct filename "/filename.php" or "/filename.php/create/user" so I can redirect to unknown.php

The 1st regular expression that I got almost works for the first part. ==============================================

request url: http://domain.com/user/create
regex: ^/([a-zA-Z0-9_]+)(/)?(.*)?$
replace http://domain.com/$1.php$2$3
makes: http://domain.com/user.php/create

Problem is it also matches http://domain.com/user.php/create

If someone could help me with both regular expressions that would be great.

like image 587
Cecil Zorg Avatar asked May 31 '11 20:05

Cecil Zorg


2 Answers

If you want to match those .php cases you can try this:

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

See here on Regexr

If you want to avoid those cases try this:

^/([a-zA-Z0-9_]+)(?!\.php)(?:(/)(.*)|)$

See here on Regexr

The (?!\.php) is a negative look ahead that ensures that there is no .php at this place.

like image 67
stema Avatar answered Oct 01 '22 00:10

stema


When all you have is a hammer...

While this probably could be solved with a regexp, it is probably the wrong tool for the job, unless you have constraints that MANDATE the use of regexps.

Split the string using '/' as the delimiter, see whether the first component ends with '.php'; if so, reject it, otherwise append '.php' to the first component and join the components back using '/'.

like image 21
zvrba Avatar answered Sep 30 '22 23:09

zvrba