What I want
I want to get from a URL
the domain
part so from http://example.com/
-> example.com
I think the following regexp might answers your question.
This diagram explains how it works, or rather why it works :-)
$regexp = '/.*\/\/([^\/:]+).*/';
// www.stackoverflow.com
echo preg_replace($regexp, '$1', 'http://www.stackoverflow.com/questions/ask');
// google.de
echo preg_replace($regexp, '$1', 'http://google.de/?q=hello');
// it works for the other input tests too ;-)
preg_match('/(http(|s)):\/\/(.*?)\//si', 'http://www.example.com/page/?bla=123#!@#$%^&*()_+', $output);
// $output[0] ------------> https://www.example.com/
I use:
$domain = parse_url('http://' . str_replace(array('https://', 'http://'), '', $url), PHP_URL_HOST);
Because parse_url
doesn't return host key when schema is missing in $url
.
There's no need to use a regex for this. PHP has an inbuilt function to do just this. Use parse_url():
$domain = parse_url($url, PHP_URL_HOST);
Here's my quick and dirty solution.
http://([^/]+).*
I haven't tested it, but it should grab anything between the http://
and the first slash.
if (preg_match('/http:\/\/([^\/]+)\//i', $target_string, $matches)) {
$domain = $matches[1];
}