我需要一个从 URL 生成纯域名的 php 函数。因此,此函数必须从 URL 中删除 http://
、www
和 /
(斜线)部分(如果这些部分存在)。这是示例输入和输出:
输入-> http://www.google.com/ |输出 -> google.com
输入-> http://google.com/ |输出 -> google.com
输入 -> www.google.com/|输出 -> google.com
输入 -> google.com/|输出 -> google.com
输入-> google.com |输出 -> google.com
我检查了 parse_url
函数,但没有返回我需要的内容。
因为,我是 PHP 的初学者,所以对我来说很难。如果您有任何想法,请回答。
提前致谢。
最佳答案
$input = 'www.google.co.uk/';
// in case scheme relative URI is passed, e.g., //www.google.com/
$input = trim($input, '/');
// If scheme not included, prepend it
if (!preg_match('#^http(s)?://#', $input)) {
$input = 'http://' . $input;
}
$urlParts = parse_url($input);
// remove www
$domain = preg_replace('/^www\./', '', $urlParts['host']);
echo $domain;
// output: google.co.uk
可以正确处理所有示例输入。
关于php - 如何从 PHP 中的 URL 中删除 http ://, www 和斜杠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364242/