1

I'm trying to write a regex expression in PHP that will load content in all locations specified, or every location except those specified.

#load content everywhere EXCEPT locations expressed
<?php if (preg_match('/\/(contact\/|news\/|index\.html)/', $_SERVER['REQUEST_URI']) === 0): ?>
<div class="greeting">Bonjour</div>
<?php endif; ?>

#load content on locations expressed
<?php if (preg_match('/\/(contact\/|news\/|index\.html)/', $_SERVER['REQUEST_URI']) === 1): ?>
<div class="greeting">Konichiwa</div>
<?php endif; ?>

The problem I'm having is that I can't get the root of my website /index.html(specifically http://example.com/index.html, nowhere else) to work alongside the wildcards for any page in /contact/ or /news/.

To summarize again: /contact/* (any page in contact), /news/* (any page in /news/), /index.html (root of website)

I've tried a few different ways of adding the slash before index.html, but it either didn't work or returned a PHP error.

1 Answer 1

1

Make sure you use anchor ^ (line start) make sure you match URI from root:

if (preg_match('#^/(contact/|news/|index\.html|$)#', $_SERVER['REQUEST_URI']))

I also changed regex delimiter to # so that you can avoid escaping / in your regex.

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

4 Comments

Sorry for the delayed response. I tried it, but it still doesn't seem to be recognizing that index.html is the root like example.com/ or example.com. As it did before, it still works for /contact/* and /news/*, but no matter what I do, it doesn't seem to recognize the root of the website.
What was the URL in your browser when you tested it?
I tried example.com, example.com/. It works with example.com/index.html, but I thought in this case it understood it on the server side since index.html was being loaded at the root when you just went to example.com. What can I do to define the front page of the domain in the regex instead of index.html?
Ok I made an edit to take care of just example.com in the URL. Pls check.

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.