我需要一个函数来从URL中提取名称。
当输入为www.google.com
时,我希望输出为google
。
www.facebook.com
- > facebook
经过几次搜索后,我发现了这个函数parse_url($url, PHP_URL_HOST);
使用此功能,当我输入www.google.com/blahblah/blahblah
时,我得到输出为www.google.com
答案 0 :(得分:1)
我认为只有一种中途可靠的方法,你需要为它创建一个类;我个人使用类似namespace\Domain extends namespace\URI
之类的东西 - 一个域,基本上是URI的一个子集 - 从技术上讲,我创建了两个类。
您的域可能需要一个静态类成员来保存有效TLD列表,这可能也存在于URI类中,因为您可能希望将其重用于其他子类。
namespace My;
class URI {
protected static $tldList;
private static $_tldRepository = 'http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1';
protected $uri;
public function __construct($sURI = "") {
if(!self::$tldList) {
//static method to load the TLD list from Mozilla
// and parse it into an array, which sets self::$tldList
self::loadTLDList();
}
//if the URI has been passed in - set it
if($sURI) $this->setURI($sURI);
}
public function setURI($sURI) {
$this->uri = $sURI; //needs validation and sanity checks of course
}
public function getURI() {
return $this->uri;
}
//other methods ...
}
实际上,我实际上将TLD列表的副本复制到服务器上的文件并使用它,并且每6个月更新一次,以避免在首次创建URI对象时读取完整TLD列表的开销。任何页面。
现在您可能有一个扩展\ My \ URI的Domain子类,并允许您将URI分解为组件部分 - 可能有一种方法可以删除TLD(基于您加载到的TLD列表) parent::$tldList
来自mxr.mozilla.org
的{{1}}一旦您取出有效的顶级域名,它的左侧(最后.
和顶级域名之间)应该是域名,任何剩下的内容这将是子域名。
您也可以根据需要提取方法来提取数据。
答案 1 :(得分:0)
虽然我同意关于剥离顶级域名的评论
,但这可以满足您的要求preg_match("/([^\.\/]+)\.[a-z\.]{2,6}$/i", "http://www.google.com", $match);
echo $match[1];
它与TLD之前的部分基本匹配。我相信RFC规定最长的公共TLD可以是6个字符。 TLD部分不是万无一失的,但它适用于大多数输入。
答案 2 :(得分:0)
Regex和parse_url()不是您的解决方案。
您需要使用Public Suffix List的软件包,只有这样您才能正确提取具有二级,三级TLD(co.uk,a.bg,b.bg等)和多级子域的域名
我建议使用TLD Extract。这里是代码示例:
$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse('www.google.com/blahblah/blahblah');
$result->getHostname(); // will return (string) 'google'
$result->getRegistrableDomain(); // will return (string) 'google.com'