0

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

jazuly aja
  • 89
  • 10
  • Are you asking how to simply extract the domain (`www.web.org`), or how to replace the domain `www.web.org` with `www.piratefiles.org` when there's an **unknown** number of subfolders? For the latter, you'd first want to extract the domain and then simply append the final segment. – Obsidian Age Jan 15 '18 at 01:10
  • ah, my bad. im already fix it using `preg_match` – jazuly aja Jan 15 '18 at 01:15

2 Answers2

1

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
Toto
  • 89,455
  • 62
  • 89
  • 125
0

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.

t j
  • 7,026
  • 12
  • 46
  • 66
jazuly aja
  • 89
  • 10