<?php if (preg_match('/\/(contact|news)\//', $_SERVER['REQUEST_URI']) === 1): ?>
<a href="/">link</a>
<?php endif; ?>
Is there a way I can also specify a single page such as /index.html
in a regex specifying folders in a php if
?
Written like this:
<?php
if (preg_match('/\/(contact\/|news\/|index\.html)/', $_SERVER['REQUEST_URI'])):
?>
You can define as many pages as you like (note the last /
has been moved). Though, that could very quickly become unwieldy.
You may also wish to consider using preg_quote :
<?php
$startsWith = array(
'contact/',
'news/',
'index.html'
);
foreach($startsWith as &$string) {
$string = preg_quote($string);
}
if (preg_match('/\/(' . implode('|', $startsWith) . ')/', $_SERVER['REQUEST_URI'])): ?>
Which, especially if unfamiliar with regex syntax, would make managing things a little easier.
Try the below :
<?php if (preg_match('/\/(contact|news)\/index\.html/', $_SERVER['REQUEST_URI']) === 1): ?>
<a href="/">link</a>
<?php endif; ?>
UPDATE
Based on your comment below this is the code that should work :
<?php
// you can add .* after index\.html you want to match index.html with get variables
echo preg_match('/\/(index\.html.*|contact\/.*|news\/.*)/','/index.html');
// or just make it strict to match only index.html
echo preg_match('/\/(index\.html|contact\/.*|news\/.*)/','/index.html');
echo '<br>';
echo preg_match('/\/(index\.html|contact\/.*|news\/.*)/','/contact/blablabla');
echo '<br>';
echo preg_match('/\/(index\.html|contact\/.*|news\/.*)/','/news/blablabla');
?>
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.