Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function for retrieving the "first part" of a URL?

Tags:

php

built-in

Is there a PHP function for retrieving the "first part" of a URL, similar to how dirname/basename act on file paths?

Something along the lines of

echo "url_basename('example.com/this_post/12312')"

which would return

example.com
like image 739
sam Avatar asked Jan 18 '26 18:01

sam


2 Answers

parse_url should do this reliably.

like image 170
Adrian Frühwirth Avatar answered Jan 20 '26 08:01

Adrian Frühwirth


Here is the code to output example.com with your given URL:

$url = 'example.com/this_post/12312';

if (strpos($url,'http') === FALSE) {
    $url = 'http://'.$url;
}

$arrURLParts = parse_url($url);
$host = $arrURLParts['host'];
echo $host;

Warning: if you omit the part to ensure the URL starts with http then parse_url would return an empty host and put 'example.com/this_post/12312' into $arrURLParts['path'] instead.

like image 38
Kmeixner Avatar answered Jan 20 '26 06:01

Kmeixner