G.I Joe
G.I Joe

Reputation: 73

Get base url from string

I have a simple script like this

$data = "http://example.com/index.php?data=data&value=value";

How to get base url from $data? The output will be like this

http://example.com

The output without this text " /index.php?data=data&value=value

Upvotes: 7

Views: 9680

Answers (4)

Yasir Ijaz
Yasir Ijaz

Reputation: 1043

$url= parse_url($url, PHP_URL_HOST);

Why can't we just use this. Worked for me.

Upvotes: 0

Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10714

You can use pathinfo included scheme and hostname.

$url = "http://example.com/index.php?data=data&value=value";
$base_url = pathinfo($url, PATHINFO_DIRNAME);
echo $base_url;

Output:

http://example.com

Upvotes: 1

Devsi Odedra
Devsi Odedra

Reputation: 5322

Use parse_url()

$url = "http://example.com/index.php?data=data&value=value";
$url_info = parse_url($url);
echo $url_info['host'];//hostname

Additionally $user_info contain below

[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor

SO you can get http by scheme

you can do something like :

echo $url_info['scheme'] . '://' . $url_info['host'];//http://example.com

Upvotes: 17

Daniel Doctor
Daniel Doctor

Reputation: 148

Check Parsing Domain From URL In PHP

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'

Upvotes: 0

Related Questions