note 42086 deleted from function.substr by nlopess
| From: | nlopess@php.net | Date: | Mon, 03 May 2004 13:38:09 +0000 |
| Subject: | note 42086 deleted from function.substr by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-69141@lists.php.net to get a copy of this message | ||
Note Submitter: sp4mh0l3@hotmail.com
----
I wanted to "clean up" a URL to get domain and sub-domain only.
This is what I ended up with:
<?php
//This is the example url we want to play with
$url = 'http://www.somewhere.com/somefile.htm';
print("Before: $url<br>\n");
//Make a function for this simple operation
function urltodomain($url) {
//Check if the string actually contains "http://"
if(strstr($url, 'http://')) {
// "http://" = 7 characters
$url = substr($url, 7);
//Reverse strstr to omit "/somefile.htm..."
return substr($url, 0, strlen($url) - strlen(strstr($url, '/')));
} else {
//Could not find "http://" in the url, return the url as
it is instead
return $url;
}
}
//See if it works
print('After: ' . urltodomain($url) . "<br>\n");
//This should return:
//Before: http://www.somewhere.com/somefile.htm<br>
//After: www.somewhere.com<br>
?>
This function is simple, but not very flexible. The URL could be from some other protocol (https://
for instance), so a elseif{} could be added in the function for each protocol (or some way to check
how many characters the first substr() should eat).