PHP Remove Domain Name Extension from String - php

I was wondering of the best way of removing certain things from a domain using PHP.
For example:
"http://mydomain.com/" into "mydomain"
or
"http://mydomain.co.uk/" into "mydomain"
I'm looking for a quick function that will allow me to remove such things as:
"http://", "www.", ".com", ".co.uk", ".net", ".org", "/" etc
Thanks in advance :)

To get the host part of a URL use parse_url:
$host = parse_url($url, PHP_URL_HOST);
And for the rest see my answer to Remove domain extension.

Could you use string replace?
str_replace('http://', '');
This would strip out 'http://' from a string. All you would have to do first is get the current url of the page and pass it through any string replace you wanted to..

I would str_replace out the 'http://' and then explode the periods in the full domain name.

You can combine parse_url() and str_* functions, but you'll never have correct result if you need cut domain zone (.com, .net, etc.) from your result.
For example:
parse_url('http://mydomain.co.uk/', PHP_URL_HOST); // will return 'mydomain.co.uk'
You need use library that uses Public Suffix List for handle such situations. I recomend TLDExtract.
Here is a sample code:
$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse('mydomain.co.uk');
$result->getHostname(); // will return 'mydomain'
$result->getSuffix(); // will return 'co.uk'
$result->getFullHost(); // will return 'mydomain.co.uk'
$result->getRegistrableDomain(); // will return 'mydomain.co.uk'

Related

get domain name from link with a fast and reliable method

Currently I am using this code to get the domain name (without www. or domain ending like .com):
explode('.', $url)[1];
Due to the fact that this code is in a loop it takes very long to handle it. Furthermore it can not get "example" from http://example.com/asd/asd.asd.html. Is there another and faster way to solve this?
Thank you for any answer in advance!
best greetings
use parse_url()
$host = parse_url($url, PHP_URL_HOST);
PHP_URL_HOST returns the Host
Further, use a Regex to get the desired Part of the Host:
$result = preg_match('/^(?:www\.)?([^\.]+)/', $match);

Remove slash from final string and GET

So earlier I was using http://localhost/profile.php?username=joe but now I'm using htaccess to make the URL look nice, so this is what it now looks like http://localhost/joe. Now here's the issue, before I did this
$username = $_GET['username'];
And then use it to get the username, but now how would I do it? I've seen other posts, but they seem to use longer and more complex URLs.
I can do this
$url = 'http://localhost/joe';
echo parse_url($url, PHP_URL_PATH);
And it seems to work fine, but I get a / before the actual result so I get /joe, and I want joe. I've also tried stripslashes but that didn't seem to work. So any ideas?
Trim the result on the left site to avoid removing or replacing slashes that are part of the actual value.
$result = ltrim($path, '/');
You can also use explode and array_pop.
$url = 'http://localhost/joe';
echo array_pop(explode("/", $url))
Use str_replace(). Like this
$url = 'http://localhost/joe';
$final = parse_url($url, PHP_URL_PATH);
$result = str_replace('/','',$final);
echo $result;
stripslashes() works for backward slashes, not forward slashes
Just a substr call should also work:
$url = 'http://localhost/joe';
echo substr(parse_url($url, PHP_URL_PATH), 1); // joe
You can learn about placeholders in routes. Try this article
Route Parameters
Route parameters can be used to insert placeholders into your route definition. This will effectively create a pattern in which URI segments can be collected and passed to the application’s logic handler.
This might sound a little confusing, but when you see it in action everything will fall into place. Here we go...
<?php
// app/routes.php
// routes for the books section
Route::get('/books', function()
{
return 'Books index.';
});
Route::get('/books/{genre}', function($genre)
{
return "Books in the {$genre} category.";
});
Also there is basename()
echo basename('http://localhost/joe'); //joe
It's better to use this rule or mod proxy to rewrite REQUEST_URI:
RewriteCond %{REQUEST_URI}
Then you can get your parameter and remove its slashes easily with trim($_SERVER['REQUEST_URI'],'/').

Remove certain part of string in PHP [duplicate]

This question already has answers here:
Get domain name (not subdomain) in php
(18 answers)
Closed 10 years ago.
I've already seen a bunch of questions on this exact subject, but none seem to solve my problem. I want to create a function that will remove everything from a website address, except for the domain name.
For example if the user inputs: http://www.stackoverflow.com/blahblahblah I want to get stackoverflow, and the same way if the user inputs facebook.com/user/bacon I want to get facebook.
Do anyone know of a function or a way where I can remove certain parts of strings? Maybe it'll search for http, and when found it'll remove everything until after the // Then it'll search for www, if found it'll remove everything until the . Then it keeps everything until the next dot, where it removes everything behind it? Looking at it now, this might cause problems with sites as http://www.en.wikipedia.org because I'll be left with only en.
Any ideas (preferably in PHP, but JavaScript is also welcome)?
EDIT 1:
Thanks to great feedback I think I've been able to work out a function that does what I want:
function getdomain($url) {
$parts = parse_url($url);
if($parts['scheme'] != 'http') {
$url = 'http://'.$url;
}
$parts2 = parse_url($url);
$host = $parts2['host'];
$remove = explode('.', $host);
$result = $remove[0];
if($result == 'www') {
$result = $remove[1];
}
return $result;
}
It's not perfect, at least considering subdomains, but I think it's possible to do something about it. Maybe add a second if statement at the end to check the length of the array. If it's bigger than two, then choose item nr1 instead of item nr0. This obviously gives me trouble related to any domain using .co.uk (because that'll be tree items long, but I don't want to return co). I'll try to work around on it a little bit, and see what I come up with. I'd be glad if some of you PHP gurus out there could take a look as well. I'm not as skilled or as experienced as any of you... :P
Use parse_url to split the URL into the different parts. What you need is the hostname. Then you will want to split it by the dot and get the first part:
$url = 'http://facebook.com/blahblah';
$parts = parse_url($url);
$host = $parts['host']; // facebook.com
$foo = explode('.', $host);
$result = $foo[0]; // facebook
You can use the parse_url function from PHP which returns exactly what you want - see
Use the parse_url method in php to get domain.com and then use replace .com with empty string.
I am a little rusty on my regular expressions but this should work.
$url='http://www.en.wikipedia.org';
$domain = parse_url($url, PHP_URL_HOST); //Will return en.wikipedia.org
$domain = preg_replace('\.com|\.org', '', $domain);
http://php.net/manual/en/function.parse-url.php
PHP REGEX: Get domain from URL
http://rubular.com/r/MvyPO9ijnQ //Check regular expressions
You're looking for info on Regular Expression. It's a bit complicated, so be prepared to read up. In your case, you'll best utilize preg_match and preg_replace. It searches for a match based on your pattern and replaces the matches with your replacement.
preg_match
preg_replace
I'd start with a pattern like this: find .com, .net or .org and delete it and everything after it. Then find the last . and delete it and everything in front of it. Finally, if // exists, delete it and everything in front of it.
if (preg_match("/^http:\/\//i",$url))
preg_replace("/^http:\/\//i","",$url);
if (preg_match("/www./i",$url))
preg_replace("/www./i","",$url);
if (preg_match("/.com/i",$url))
preg_replace("/.com/i","",$url);
if (preg_match("/\/*$/",$url))
preg_replace("/\/*$/","",$url);
^ = at the start of the string
i = case insensitive
\ = escape char
$ = the end of the string
This will have to be played around with and tweaked, but it should get your pointed in the right direction.
Javascript:
document.domain.replace(".com","")
PHP:
$url = 'http://google.com/something/something';
$parse = parse_url($url);
echo str_replace(".com","", $parse['host']); //returns google
This is quite a quick method but should do what you want in PHP:
function getDomain( $URL ) {
return explode('.',$URL)[1];
}
I will update it when I get chance but basically it splits the URL into pieces by the full stop and then returns the second item which should be the domain. A bit more logic would be required for longer domains such as www.abc.xyz.com but for normal urls it would suffice.

Check URL for a folder

How can I check the URL path for certain folders? I ask so that if we're in a certain folder, we can make a tab selected in the nav bar (just apply a style to that specific li).
So far I know
$pagePath = $_SERVER['REQUEST_URI'];
So I can get a return that says something like /music/song/120/ (or whatever it is). What kind of php function can I use that says
if $pagePath has "music", then do this. Meaning, if the path is /music/ or /music/song, I should be able to
I plan on using this multiple times,
if $pagePath has downloads do this
if $pathPath has band do this
and so on.
Any suggestions?
You could explode() the path on / and then use in_array() to check for existence.
However, this could yield problems with paths like /bands/something/music where the state would depend on whether you check for bands before music or vice versa. In that case you could explode() with $limit = 2 (to get only two parts, i.e., split on first / only) and compare your predefined path segments to the first part of the exploded path.
E.g.
$path = trim('/bands/something/music', '/');
$parts = explode('/', $path, 2); // ['bands', 'something/music']
switch ($parts[0]) {
case 'music':
// ...
case 'bands':
// ...
}
Try strpos()
e.g.
if(strpos($_SERVER['REQUEST_URI'],'music')>0)
{
# URL contains music
}
A quick way: you could use strpos: http://www.php.net/manual/en/function.strpos.php

Remove Subdomains from Form Post

How would I go about extracting just the base URl from a long string that was inputted into a form?
Example:
User inputs: http://stackoverflow.com/question/ask/asdfasneransea
Program needs just: http://stackoverflow.com and not /question/ask/asdfasneransea
What is the easist way to do this using PHP?
You can simply use parse_url()
$url = parse_url('http://example.com/foo/bar');
$host = $url['host']; // example.com
Use the parse_url function to get the separate parts of the URL, then reassemble the parts you are looking for.

Categories