如何从PHP中的URL删除http://,www和斜杠? [英] How to remove http://, www and slash from URL in PHP?

查看:398
本文介绍了如何从PHP中的URL删除http://,www和斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个PHP函数,该函数从URL生成纯域名.因此,如果存在URL,则必须从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的初学者,所以这对我来说很难.如果您有任何想法,请回答.
提前感谢.

I need a php function which produce a pure domain name from URL. So this function must be remove http://, www and /(slash) parts from URL if these parts exists. Here is example input and outputs: Input - > http://www.google.com/ | Output -> google.com
Input - > http://google.com/ | Output -> google.com
Input - > www.google.com/ | Output -> google.com
Input - > google.com/ | Output -> google.com
Input - > google.com | Output -> google.com

I checked parse_url function, but doesn't return what I need. Since, I'm beginner in PHP, it was difficult for me. If you have any idea, please answer.
Thanx in advance.

推荐答案

$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

可以正确使用所有示例输入.

Works correctly with all your example inputs.

这篇关于如何从PHP中的URL删除http://,www和斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆