[英]how can I use php if regex for both folders and single pages
<?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
? 有没有办法我也可以在正则表达式中指定单个页面(例如/index.html
,以指定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 : 您可能还希望考虑使用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 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');
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.