[英]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; ?>
有沒有辦法我也可以在正則表達式中指定單個頁面(例如/index.html
,以指定php if
文件夾?
像這樣寫:
<?php
if (preg_match('/\/(contact\/|news\/|index\.html)/', $_SERVER['REQUEST_URI'])):
?>
您可以定義任意多個頁面(請注意最后一個/
已被移動)。 不過,這很快就會變得難以處理。
您可能還希望考慮使用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'])): ?>
尤其是如果不熟悉正則表達式語法的話,這將使管理工作變得更加容易。
請嘗試以下方法:
<?php if (preg_match('/\/(contact|news)\/index\.html/', $_SERVER['REQUEST_URI']) === 1): ?>
<a href="/">link</a>
<?php endif; ?>
UPDATE
根據您在下面的評論,這是應該起作用的代碼:
<?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.