2

I would like a regex to replace the .html file extension with a / so www.example.com/page.html becomes www.example.com/page/. I want to also exclude a folder from this rule so anything within www.example.com/specialdir/ should be excluded.

EDIT: This will be used in php

3
  • What flavour of regex? In what language or editor? Commented Sep 28, 2011 at 13:06
  • this will be used in php Commented Sep 28, 2011 at 13:07
  • In what context does the URL appear? Is it by itself or is it just one part of a longer string? Is there more than one in a longer string? Will the URL ever have query or fragments? Its always helpful to provide some desired before and after representative examples. Commented Sep 28, 2011 at 13:37

2 Answers 2

3

Better to use htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L,QSA]

Source: Snipplr

So it will change all http://somesite/someurl to http://somesite/someurl.html in server side.

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

3 Comments

I want it the other way round....remove .html and not add. Also I want to add an exception where the rule does not apply to a certain folder
@thearchitect, do some research on htaccess and mod_rewrite. This is probably the answer you're looking for.
@thearchitect my code does not redirect user to .html page. It does the change in server side and user sees in taskbar: somesite.com/somepage instead of somesite.com/somepage.html
1

Search for

(www\.example\.com/(?!specialdir/).*)\.html$

and replace all with \1 or $1, depending on your regex implementation.

EDIT: In PHP:

$result = preg_replace('%(www\.example\.com/(?!specialdir/).*)\.html$%', '\1', $subject);

Comments

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.