需要正则表达式来获取域 + 子域 [英] Need regex to get domain + subdomain

查看:50
本文介绍了需要正则表达式来获取域 + 子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在这里使用这个函数:

So im using this function here:

function get_domain($url)
{
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
    return $regs['domain'];
  }
  return false;
}

$referer = get_domain($_SERVER['HTTP_REFERER']);

我需要的是另一个正则表达式,如果有人愿意帮忙的话.正是我需要它来获取整个域,包括子域.

And what i need is another regex for it, if someone would be so kind to help. Exactly what i need is for it to get the whole domain, including subdomains.

可以说是我现在遇到的一个真正的问题.当人们从示例中创建博客链接时:myblog.blogger.com引用 URL 将只是 blogger.com,这并不理想..

Lets say as a real problem i have now. When people blogging link from example: myblog.blogger.com The referer url will be just blogger.com, which is not ideal..

因此,如果有人可以帮助我,我可以将包含子域作为上述函数的正则表达式代码,我非常感谢它!

So if someone could help me so i can get the including subdomain as regex code for the function above, id apreciate it alot!

谢谢!

推荐答案

此正则表达式应匹配字符串中的域,包括任何配音域:

This regex should match a domain in a string, including any dubdomains:

/([a-z0-9|-]+\.)*[a-z0-9|-]+\.[a-z]+/

翻译成粗略的英语,它的功能是这样的:匹配字符串的第一部分,其中包含 'sometextornumbers.sometext',还包括任意数量的 'sometextornumbers'.可能在它之前.

Translated to rough english, it functions like this: "match the first part of the string that has 'sometextornumbers.sometext', and also include any number of 'sometextornumbers.' that might preceed it.

在这里查看它的实际效果:http://regexr.com?2vppk

See it in action here: http://regexr.com?2vppk

请注意,该链接中的多行和全局标志只是为了能够匹配整个测试文本块,因此如果您只将一行传递给正则表达式,则不需要

Note that the multiline and global flags in that link are only there to be able to match the entire blob of test-text, so you don't need if you're passing only one line to the regex

这篇关于需要正则表达式来获取域 + 子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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