如何将域名后的所有内容转换为字符串 [英] How to get everything after the domain name into a string
问题描述
我的目标是将域名后的所有内容都转换为字符串.如在mysite.com/page/page2中那样,将导致字符串"page/page2".我可以这样做,但是,例如,当站点在子文件夹中而不是在根目录中时,它开始给我带来问题,然后该站点所在的文件夹也将包含在字符串中,并且如果我不使用mod_rewrite来获得漂亮的链接,它还将在字符串中添加index.php.
My goal is to get everything after the domain name into a string. As in mysite.com/page/page2 would result in a string "page/page2". That I can do, however it starts giving me problems when, for example, the site is in a subfolder and not in root, then the folder the site is in will also be included in the string and if I'm not using mod_rewrite to get pretty links, it will also add index.php to the string.
因此,我需要一两个技巧,以使脚本了解网站是否位于子文件夹(如mysite.com/sitefolder/page/page2)中,并且仍然会导致字符串
So, I would need a trick or two to make the script understand whether or not the site is in a subfolder such as mysite.com/sitefolder/page/page2 and that it would still result in a string
page/page2
如果该站点不使用mod_rewrite并且url为mysite.com/sitefolder/index.php/page/page2,则仍然会产生字符串
If the site doesn not use mod_rewrite and the url is mysite.com/sitefolder/index.php/page/page2, it would still result in a string
page/page2
请记住,我在配置文件中定义了URL和USE_MOD_REWRITE,因此不需要魔术.我只是不知道如何去获得那个字符串.我知道我可以做$ _SERVER ['REQUEST_URI']来获取字符串,但是index.php仍然在其中.很抱歉,如果我的解释不够好,但是所有帮助我们都将受到感激.
Keep in mind that I have URL and USE_MOD_REWRITE defined in a config file, so no need for magic. I just have no idea how to go about getting that string. I know I could do $_SERVER['REQUEST_URI'] to get the string, but then index.php would still be in it. I'm sorry if I didn't explain well enough, but all help is appreciated.
推荐答案
- 通过解析请求uri获取路径
- 从字符串末尾删除最终的脚本名称(例如index.php)
-
对所有斜杠进行斜线修饰
- get the path by parsing the request uri
- remove eventual script name from the end of the string (e.g. index.php)
rtrim any trailing slashes
$request = parse_url($_SERVER['REQUEST_URI']); $path = $request["path"]; $result = rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');
编辑
$request = parse_url($_SERVER['REQUEST_URI']); $path = $request["path"]; $result = trim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/'); $result = explode('/', $result); $max_level = 2; while ($max_level < count($result)) { unset($result[0]); } $result = '/'.implode('/', $result);
这篇关于如何将域名后的所有内容转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!