Change language

A program to get a subdomain url using PHP

|
Examples :
Input: subdomain.example.com Output: subdomain Input: contribute.engineerforengineer.org Output: contribute
Method 1: PHP | Function explode() :The explode() function - it is a built-in function in PHP that is used to split a string into different lines. The explode() function splits the string based on line separators, that is, it splits the string wherever the separator character is. This function returns an array containing strings formed by splitting the original string.Syntax:
array explode (separator, OriginalString , NoOfElements)
Use the explode() function to get the subdomain from the URL. Getting a subdomain using explode() is easier than getting a subdomain using preg_split().Example 1: $URL = "subdomain.example.com" ;  
// Split the string into an array $arr = explode ( ’.’ , $URL );  
// Get the first element of the array $subdomain = $arr [0]; echo $subdomain ;  
?>
Exit:
subdomain
Example 2: $URL = " contribute.engineerforengineer.org " ;  
// Split the string into an array $arr = explode ( ’.’ , $URL );  
// Get the first element of the array $subdomain = $arr [0]; echo $subdomain ;  
?>
Exit:
contribute
Method 2: PHP | Function preg_split() :function preg_split() - it is a built-in function in PHP that is used to convert a given string to an array using regular expressions. If the match fails, an array with a single element containing the input string will be returned.Syntax:
array preg_split ($pattern, $subject, $limit, $flag)
Use the preg_split() function to get the subdomain from the URL. Passing a Regular Expression as a parameter to a function and it strips the URL.Example 1: < ? php $URL = "contribute.engineerforengineer.org" ;  
// Escape ’. ’ as a special character for a regular expression. $arr = preg_split ( ’[.]’ , $URL ) ; $subdomain = $arr [0]; echo $subdomain ; ?>
Exit:
contribute
Example 2: $URL = " ide.engineerforengineer.org " ;  
// Escape ’. ’ as a special character for a regular expression. $arr = preg_split ( ’[.]’ , $URL ) ; $subdomain = $arr [0]; echo $subdomain ;  
?>
Exit:
ide
SO 1 data error