说我有一个名为redirections.txt的文件,如下所示:
www: http://www.example.com/hub/
icloud: http://www.example.com/icloud/
dev: http://www.example.com/development/latest/projects.php
我如何将该文本文档处理为domain-prefix: redirect-url
? (或"如果$ _SERVER [' HTTP_HOST']等于domain-prefix.example.com,请转到redirect-url")
目前我有:
$file = file('redirections.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($file as $line => $cont){
preg_match('/(*.?): http:\/\/www.example.com\/(*.?)\//', $cont, $matches);
print_r($matches); // Debug. Was trying to see if it worked.
}
答案 0 :(得分:1)
您可以使用explode()
拆分该行:
$split = explode(': ', $cont);
if (count($split) == 2) {
list ($domain_prefix, $redirect_url) = $split;
if ($_SERVER['HTTP_HOST'] == "$domain_prefix.example.com") {
header("Location: $redirect_url");
exit();
}
}
答案 1 :(得分:0)
可能有更好的方法来实现您想要的功能,但如果您需要使用已经提供的代码,请尝试以下方法:
foreach($file as $line => $cont){
preg_match('/(?P<domain>\w+): http:\/\/www.example.com(?P<path>\/.*)/', $cont, $matches);
print_r($matches); // Debug.