[英]Parsing out “site.com” from a passed variable in PHP?
I'm passing through a variety of URLs in a global variable called target_passthrough, so the URL of a page might look like: http://www.mysite.com/index.php?target_passthrough=example.com 我正在通过名为target_passthrough的全局变量传递各种URL,因此页面的URL可能类似于: http ://www.mysite.com/index.php?target_passthrough=example.com
Or something like that. 或类似的东西。 Formats for that variable may be a variety of things such as (minus quotes): 该变量的格式可能多种多样,例如(减引号):
Please note how some of those have periods as the first character such as 2,5, and 6. 请注意,其中有些字符的第一个字符是句点,例如2,5和6。
Now, what I am trying to do is pull out just "example.com" from any of those possible scenarios with PHP and store it to a variable to echo out later. 现在,我想做的是从任何可能的PHP场景中仅提取“ example.com”,并将其存储到变量中,以便稍后回显。 I tried parse_url but it gives me the "www" when that is present, which I do not want. 我试过parse_url,但是当我出现时,它会给我一个“ www”,这是我不想要的。 In instances where the url is just "example.com" it returns a null value. 在网址只是“ example.com”的情况下,它将返回一个空值。
I don't really know how to do regex matching or if that is even what I need so any guidance would be appreciated--not really that advanced at php. 我真的不知道该怎么做正则表达式匹配,或者即使那是我需要的,所以任何指导都将不胜感激-在php上并不是那么先进。
As you pointed out, you can use parse_url to do much of the work for you and then simply strip off the www
or leading dot if it is present. 如您所指出的,您可以使用parse_url为您完成许多工作,然后简单地删除www
或前导点(如果存在)。
An alternative strategy of taking the last two "words" won't always work because there are domains like www.example.co.uk
. 采用最后两个“单词”的替代策略并不总是可行,因为存在诸如www.example.co.uk
类的域。 Using this strategy would give you co.uk
instead of example.co.uk
. 使用此策略将为您提供co.uk
而不是example.co.uk
。 There is no simple rule for determining which parts are the domain or the sub-domain. 没有简单的规则来确定哪些部分是域或子域。
parse_url() outputs an array the different parts of the URL. parse_url()输出URL的不同部分组成的数组。 You are getting null values because you are only referencing the first item in the array. 因为只引用数组中的第一项,所以得到空值。 parse_url() parse_url()
Array (
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.