Reputation: 5439
I have an input field where the user can type an URL. He could type the URL in many different ways, for example:
No matter how he types it, I want to echo it like this: example.com
Only when it is an sub domain, then it should look like this: subdomain.example.com
How can I do this?
Upvotes: 0
Views: 270
Reputation: 5439
I allow myself to answer my own question:
$url = 'https://www.example.com/index.php';
$str = preg_replace('#^https?://|www.#', '', rtrim($url,'/'));
echo (strpos($str,'/') !== false) ? strstr($str, '/', true) : $str;
You can define $url however you want. The result is always example.com
Upvotes: 0
Reputation: 219924
Use parse_url()
with the PHP_URL_HOST
component as the second parameter:
$url = 'example.com/index.php';
if (preg_match("#https?://#", $url) === 0) {
$url = 'http://'.$url;
}
echo parse_url($url, PHP_URL_HOST);
(I had some help from this answer to make sure there is always a protocol attached to the URL.)
Upvotes: 2