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

时间:2013-08-03 08:18:27

标签: php regex

我正在尝试在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,而不是其他地方)与{{1}中的任何网页的通配符一起使用}或/contact/

再次总结: /news/(任何联系页面),/contact/*(/ news /中的任何页面),/news/*(网站根目录)

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

1 个答案:

答案 0 :(得分:1)

确保使用锚^(行开头)确保匹配来自root的URI:

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

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