2012-07-30 40 views
1

我知道几乎没有关于PHP,所以这可能会让人笑。php preg_match多个网址

我在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'); 
} 

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

回答

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'); 
} 
+0

谢谢,但它可能并不总是类似的网址。理想情况下,也许我需要一个数组,我可以根据需要添加其他网址。 – user460114 2012-07-30 08:02:31

+0

@ user460114请参阅我的编辑。 – xdazz 2012-07-30 08:05:38

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

尝试,

$hosts="/(site1\.com)|(site2\.com)/"; 
if (!preg_match($hosts,$host)) { 
    // do something. 
} 
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/'); 
}