user4899189
user4899189

Reputation:

Extract a single value from a preg_match() PHP

If I perform the following:

preg_match('/[a-z]+.[a-z]+$', $_SERVER['HTTP_HOST'], $domain);

with $SERVER['HTTP_HOST'] = subdomain.mydomain.com, preg_match() will create a an array $domain which contains all the matches, in this case: $domain = ["mydomain.com"]

The result I want is $domain = "mydomain.com"


My question is, is there a more elegant way to do this than:

preg_match('/[a-z]+.[a-z]+$', $_SERVER['HTTP_HOST'], $domain);
$domain = $domain[0];

Upvotes: 0

Views: 147

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

I don't know if it is more elegant or not, but it's a little more direct:

$arr = [
    'subdomain.mydomain.com',
    'mydomain.com',
    'subdo.subdomain.mydomain.com'
];

foreach ($arr as $item) {
    echo preg_replace('~(?:.*\.)?(?=.*\.)~', '', $item), PHP_EOL;
}

demo

Upvotes: 1

Related Questions