Reputation: 89
How do I use preg_replace
text/url. For example, I have a url like this: http://www.web.org/dorama/1201102144/hitoya-no-toge
. I just want to show web.org
. The url is not always same, for example sometimes it's: http://www.web.org/movies/123/no
etc.
I only know the basics of it. Here is what I tried. It still does not delete the slash
.
$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$patterns = array();
$patterns[0] = '/http:/';
$patterns[1] = '/dorama/';
$patterns[2] = '/1201102144/';
$replacements = array();
$replacements[2] = '';
$replacements[1] = '';
$replacements[0] = '';
echo preg_replace($patterns, $replacements, $url);
result when i run it //www.web.org///hitoya-no-toge
Upvotes: 0
Views: 1062
Reputation: 91373
For such a job, I'd use parse_url then explode:
$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$host = (parse_url($url))['host'];
$domain = (explode('.', $host, 2))[1];
echo $domain;
Output:
web.org
Upvotes: 1
Reputation: 89
Use preg_match
instead preg_replace
i think http://php.net/manual/en/function.preg-match.php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "{$matches[0]}"
If use https change http to https, I don't know how to make it work for http and https.
Upvotes: 0