如何使用preg_replace
text / url。例如,我有一个这样的网址:http://www.web.org/dorama/1201102144/hitoya-no-toge
。我只想展示web.org
。网址并不总是相同的,例如有时它是:http://www.web.org/movies/123/no
等。
我只知道它的基础知识。这是我试过的。它仍然不会删除slash
。
$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$patterns = array();
$patterns[0] = '/http:/';
$patterns[1] = '/dorama/';
$patterns[2] = '/1201102144/';
$replacements = array();
$replacements[2] = '';
$replacements[1] = '';
$replacements[0] = '';
echo preg_replace($patterns, $replacements, $url);
运行//www.web.org///hitoya-no-toge
答案 0 :(得分:1)
对于这样的工作,我使用parse_url然后explode:
$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$host = (parse_url($url))['host'];
$domain = (explode('.', $host, 2))[1];
echo $domain;
<强>输出:强>
web.org
答案 1 :(得分:0)
使用preg_match
代替preg_replace
我认为http://php.net/manual/en/function.preg-match.php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "{$matches[0]}"
如果使用https将http更改为https,我不知道如何使其适用于http和https。