Konda Vamshi Das February 2016

How can I explode and implode value from url

$string = 'http://india.domain.com';
$string = explode('.', $actual_link);
array_pop($string);
$string = implode(' ', $string);
echo $string;`

how can I get value only india from URL $string = "http://india.domain.com";?

Answers


Lajos Arpad February 2016

Depends on what does 'india' represent. It might represent the first word before the dot, but after the http://

$string = 'http://india.domain.com';
echo substring($string, 8, strpos($string, ".") - 8);

Or it might be something else. In general, it is better to specify what you need exactly, otherwise we can do no better than guesswork.


Ben February 2016

See parse_url():

//Source string
$string = "http://india.domain.com";

//Parse URL into array $parsed - this creates an array of
//["scheme"] => "http", ["host" => "india.domain.com"
$parsed = parse_url($string);

//Explode from "." to array $parts - this creates an array of
//[0] => "india", [1] => "domain", [2] => "com"
$parts = explode(".", $parsed["host"]);

//Echo subdomain
echo $parts[0];


Birendra Gurung February 2016

Try this code:

$string = 'http://india.domain.com';
$string = explode('.', $string);
$string = explode('//', $string[0]);
echo $string[1];


Dave F February 2016

If your URL might not contain the scheme (or protocol) (ie. http), then you can use the following code:

$string = "http://india.domain.com/path/file.html";

// Protocol is optional
$host = preg_replace('/^(?:[^:]+:\/\/)?([^\/]+)\/.*/', '\1', $string);
$parts = explode(".", $host);

print_r($parts);
echo "<br>${parts[0]}";

Post Status

Asked in February 2016
Viewed 3,679 times
Voted 14
Answered 4 times

Search




Leave an answer