开发者

Parsing text and return hostname before period with PHP

开发者 https://www.devze.com 2023-02-09 03:11 出处:网络
$hostname = \"abc.domain.com\" I just want \"abc\" and nothing after开发者_运维知识库 it.With substr and strpos:
$hostname = "abc.domain.com"

I just want "abc" and nothing after开发者_运维知识库 it.


With substr and strpos:

$host = substr($hostname, 0, strpos($hostname, '.'));

or maybe better, strstr:

$host = strstr($hostname, '.', true);

There are a lot of functions available to process strings.


Use explode():

$parts = explode('.', $hostname);
// $parts[0]


Will it always have a subdomain?

If so, you can just do

$parts = explode('.', $hostname);
$subdomain = $parts[0];

If there might not be a subdomain

$parts = explode('.', $hostname);
$subdomain = count($parts) == 3 ? $parts[0] : NULL;
0

精彩评论

暂无评论...
验证码 换一张
取 消