Sunday, December 21, 2025
HomeLanguagesProgram to get the subdomain of a URL using PHP

Program to get the subdomain of a URL using PHP

Given a URL and the task is to get the sub-domain from the given URL. Use explode() function which breaks a string into array or preg_split() function which splits the given string into array by Regular Expression.

Examples:

Input : subdomain.example.com
Output : subdomain

Input : write.geeksforgeeks.org
Output : contribute

Method 1: PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings. The explode() function splits a string based on the string delimiters, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

Syntax:

array explode( separator, OriginalString, NoOfElements )

Use explode() function to get the sub-domain from URL. Getting the sub-domain using explode() function is easier than getting sub-domain using preg_split() function.

Example 1:




<?php
  
$URL = "subdomain.example.com";
  
// Split string into array
$arr = explode('.', $URL);
  
// Get the first element of array
$subdomain = $arr[0];
  
echo $subdomain;
  
?>


Output:

subdomain

Example 2:




<?php
  
$URL = "write.geeksforgeeks.org";
  
// Split string into array
$arr = explode('.', $URL);
  
// Get the first element of array
$subdomain = $arr[0];
echo $subdomain;
  
?>


Output:

contribute

Method 2: PHP | preg_split() Function: The preg_split() function is an inbuilt function in PHP which is used to convert the given string into an array by Regular Expression. If matching fails, an array with a single element containing the input string will be returned.

Syntax:

array preg_split( $pattern, $subject, $limit, $flag )

Use preg_split() function to get the sub-domain from URL. Passing the Regular Expression as parameter to the function and it split the URL.

Example 1:




<?php
  
$URL = "write.geeksforgeeks.org";
  
// Escape '.' as special symbol for regular expression.
$arr = preg_split('[\.]', $URL); 
  
$subdomain = $arr[0];
  
echo $subdomain;
?>


Output:

contribute

Example 2:




<?php
  
$URL = "ide.geeksforgeeks.org";
  
// Escape '.' as special symbol for regular expression.
$arr = preg_split('[\.]', $URL); 
  
$subdomain = $arr[0];
  
echo $subdomain;
  
?>


Output:

ide
RELATED ARTICLES

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6911 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS