Home > Mobile >  How to get only base url php
How to get only base url php

Time:03-16

I am using the following code to get url,

<?php echo substr($links[$i],0,60); ?>

This shows full url with max 60 characters. But i want to show only base url like www.example.com

Can anyone help?

CodePudding user response:

Use parse_url from php.net parse_url

<?php
$url = "https://www.stackoverflow.com/";
echo $domain = parse_url($url, PHP_URL_HOST);
?>
Output: www.stackoverflow.com

<?php
$url = '//www.example.com/path?googleguy=googley';

// Prior to 5.4.7 this would show the path as "//www.example.com/path"
echo "<pre>";
var_dump(parse_url($url));
echo "</pre>";
?>

<?php
echo "<pre>";
var_dump(parse_url($url));
var_dump(parse_url($url, PHP_URL_SCHEME));
var_dump(parse_url($url, PHP_URL_USER));
var_dump(parse_url($url, PHP_URL_PASS));
var_dump(parse_url($url, PHP_URL_HOST));
var_dump(parse_url($url, PHP_URL_PORT));
var_dump(parse_url($url, PHP_URL_PATH));
var_dump(parse_url($url, PHP_URL_QUERY));
var_dump(parse_url($url, PHP_URL_FRAGMENT));
echo "</pre>";
?>

With echo "<pre>"; echo "</pre>"; you can style the output from var_dump, looks better

  • Related