-3
$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";?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • Are you trying to retrieve any string where 'india' is in your URL? I.e., do you want to retrieve `randomstring` from http://randomstring.domain.com ? You may want to take a look at http://stackoverflow.com/questions/5941832/php-using-regex-to-get-substring-of-a-string – Joshua Feb 08 '16 at 17:15
  • 1
    `$string = explode('.', $actual_link);` you're using the wrong variable. See here? `$string = 'http://india.domain.com';` - where does `$actual_link` come into play here? – Funk Forty Niner Feb 08 '16 at 17:17
  • http://php.net/manual/en/function.parse-url.php – Funk Forty Niner Feb 08 '16 at 17:22

4 Answers4

2

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];
Dave F
  • 1,837
  • 15
  • 20
Ben
  • 8,894
  • 7
  • 44
  • 80
  • `parse_url` doesn't recognize the host without a scheme. If the scheme is always going to be present, then I think that this is the preferred method. – Dave F Feb 08 '16 at 19:23
0

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

Try this code:

$string = 'http://india.domain.com';
$string = explode('.', $string);
$string = explode('//', $string[0]);
echo $string[1];
Birendra Gurung
  • 2,168
  • 2
  • 16
  • 29
0

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]}";
Dave F
  • 1,837
  • 15
  • 20