繁体   English   中英

php preg_match正则表达式用于多个目录和文件

[英]php preg_match regex for multiple directories and files

我正在尝试在PHP中编写一个正则表达式,该表达式将在指定的所有位置或除指定位置之外的每个位置加载内容。

#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; ?>

我遇到的问题是我无法使我的网站/index.html的根目录(特别是http://example.com/index.html ,除了其他地方)无法与通配符一起用于/contact/任何页面/contact//news/

再次总结一下: /contact/*/contact/*任何页面), /news/*/news/*任何页面),/ /index.html (网站的根目录)

我尝试了几种不同的方法在index.html之前添加斜杠,但是它不起作用或返回了PHP错误。

确保您使用锚^ (行开头),确保您匹配根目录中的URI:

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

我还将正则表达式定界符更改为#以便您可以避免在正则表达式中转义/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM