如何在URL上使用preg_replace

时间:2018-01-15 01:04:55

标签: php preg-replace str-replace

如何使用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

时的结果

2 个答案:

答案 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。