简体   繁体   English

如何在本地主机上修剪我的家庭URL

[英]How to trim my home url on the localhost

This is how I get my url on my localhost: 这是我在本地主机上获取URL的方法:

 $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    echo $url;

it returns : http://localhost/CodeSensei/menu because I am on the menu page. 它返回: http:// localhost / CodeSensei / menu,因为我在菜单页面上。

How can I trim this? 我该如何修剪? I only want " http://localhost/CodeSensei " 我只想要“ http:// localhost / CodeSensei

I know I can trim it like this 我知道我可以这样修剪

echo trim($url,"menu");

But the problem is, that "menu" is dynamic, it keep changing dependes on the page. 但是问题是,“菜单”是动态的,它不断变化取决于页面。 Is there any way to trim my url so it will always and only print " http://localhost/CodeSensei " in any page? 有什么方法可以修剪我的网址,以便它始终且仅在任何页面中显示“ http:// localhost / CodeSensei ”?

This function may help you. 此功能可能对您有帮助。 It get a url and return the url without after the last / . 它获取一个url,并返回URL而不在last /

<?php
function getSubUrl($originUrl) {
    $url = parse_url($originUrl);
    $url['scheme'] .= '://';
    $url['path'] = dirname($url['path']);

    return implode($url);
}


echo getSubUrl('http://localhost/CodeSensei/menu/123') . PHP_EOL;
// http://localhost/CodeSensei/menu
echo getSubUrl('http://localhost/CodeSensei/menu') . PHP_EOL;
// http://localhost/CodeSensei
echo getSubUrl('http://localhost/CodeSensei') . PHP_EOL;
// http://localhost/
echo getSubUrl('http://localhost/') . PHP_EOL; 
// http://localhost/
echo getSubUrl('http://localhost') . PHP_EOL;
// http://localhost

There are many ways to achieve this. 有很多方法可以实现这一目标。 You can play around with different string manipulators like explode() etc. 您可以玩弄不同的字符串操纵器,例如explode()等。

Here is a solution using explode() 这是使用explode()的解决方案

$variable =  "http://localhost/CodeSensei/menu";
$variable = (explode("/",$variable));
$url='';

for($i=2;$i<count($variable)-1;$i++)
{  
    $url .= "/".$variable[$i];
}

$final_url = "http:/".$url;

echo $final_url;

Your output 您的输出

http://localhost/CodeSensei

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM