php preg_match多个网址

时间:2012-07-30 07:59:36

标签: php

我对PHP几乎一无所知,所以这可能会让人大笑。

我在index.php中有一些代码,用于检查主机头并在找到匹配项时重定向。

if (!preg_match("/site1.net.nz/",$host)) {
    header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}

但是,我需要检查可能有多个网站。如下。

if (!preg_match("/site1.net.nz/"|"/site2.net.nz",$host)) {
    header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}

这实际上可能是我所知道的正确语法: - )

4 个答案:

答案 0 :(得分:1)

if (!preg_match("/(site1\.net\.nz|site2\.net\.nz|some\.other\.domain)/",$host)) {
    header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}

答案 1 :(得分:1)

尝试,

$hosts="/(site1\.com)|(site2\.com)/";
if (!preg_match($hosts,$host)) {
  // do something.
}

答案 2 :(得分:0)

// [12] to match 1 or 2
// also need to escape . for match real . otherwise . will match any char
if (!preg_match("/site[12]\.net\.nz/",$host)) {
    header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}

if (!preg_match("/site1\.net\.nz|site2\.net\.nz/",$host)) {
    header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}

答案 3 :(得分:0)

if (!preg_match("/(site1\.net\.nz|site2\.net\.nz)/",$host)) {
    header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}

这将是正确的RegEx语法。

假设您有一系列网址。

$array = Array('site1.net.nz', 'site2.net.nz');

foreach($array as &$url) {
   // we need to escape the url properly for the regular expression
   // eg. 'site1.net.nz' -> 'site1\.net\.nz'
   $url = preg_quote($url);
}

if (!preg_match("/(" . implode("|",  $array) . ")/",$host)) {
    header('Location: http://example.com/');
}