douluanzhao6689 2015-01-11 19:18
浏览 20
已采纳

从URL末尾删除字符

Say I have a URL with something like this:
http://website.com/website/webpage/?message=newexpense

I have the following code to try and get the the URL before the question mark:

$post_url = $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];

In this example I would get the following URL:
http://website.com/website/webpage/

I'd like to remove the webpage portion of this so the URL is:
http://website.com/website/

How can I do this?

  • 写回答

4条回答 默认 最新

  • dqo58772 2015-01-11 19:30
    关注

    You can do a similar trick using explode. Then pop the parts you don't need and implode the url back together. If you are sure that the part after '?' never contains a '/', you can replace your code with this one. If you're not sure, you should first remove the part after '/' and then run this code to remove the last part of the path.

    <?php
    $url = 'http://website.com/website/webpage/?message=newexpense';
    
    $parts = explode('/', $url);
    
    // Remove the last part from the array
    $lastpart = array_pop($parts);
    
    // If the last part is empty, or the last part starts with a '?'
    // this means there was a '/' at the end of the url, so we 
    // need to pop another part.
    if ($lastpart == '' or substr($lastpart, 0, 1) == '?')
      array_pop($parts);
    
    $url = implode('/', $parts);
    
    var_dump($url);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi