5

Given a URL:

http://mysite.com/this-is/the/path

I just want the scheme and the host I.e. http://mysite.com/

Currently I am using parse_url and then building it back up like so:

$urlParts = parse_url($url);
$newUrl = $urlParts['scheme'] . "://" . $urlParts['host'] . "/";

Is there no PHP function that can strip the path off?

1
  • 3
    Not that I know of, and arguably, there shouldn't be - seeing as 2 lines of code seem to be doing the job? The basic set of PHP's functions is enough of a bloated mess already...
    – Pekka
    Sep 27, 2013 at 0:38

3 Answers 3

6

Not that I am aware of. This is a good example of a time where you may consider writing your own public function.

public function stripUrlPath($url){
    $urlParts = parse_url($url);
    $newUrl = $urlParts['scheme'] . "://" . $urlParts['host'] . "/";
    return $newUrl;
}

Then use it throughout your code:

$newUrl = stripUrlPath($oldUrl);
0

You can use a regex:

$url = 'http://mysite.com/this-is/the/path';
$pattern = '~^(.*?//.*?)/.*~';
preg_match($pattern, $url, $matches);
echo $matches[1]; // http://mysite.com

However, I would use parse_url() and rebuild the string as you currently doing.

-3
<?php
  echo 'http://' . $_SERVER['HTTP_HOST'] . '/';
?>
5
  • -1: How about HTTPS? Also, the question is about an arbitrary url and not the current query.
    – mkf
    Sep 27, 2013 at 1:11
  • maybe he doesn't care for it Sep 27, 2013 at 1:12
  • 1
    It's good to write robust code that does not make unnecessary assumptions like this. You could easily lead yourself into a hidden bug trying to use such a function half a year later.
    – mkf
    Sep 27, 2013 at 1:18
  • some asking don't use built in functions.. so i try to help, and he also have a solution in 2 lines above... Sep 27, 2013 at 1:42
  • No offence intended. I'm not negating your will to help - I just feel that the answer could be improved. Stackoverflow is a place for all of us to learn.
    – mkf
    Sep 27, 2013 at 1:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.