doushou9028 2015-10-13 22:20
浏览 482
已采纳

PHP用str_replace()替换URL段;

I have "/foo/bar/url/" coming straight after my domain name.

What I want is to find penultimate slash symbol in my string and replace it with slash symbol + hashtag. Like so: from / to /# (The problem is not how to get URL, but how to handle it)

How this could be achieved? What is the best practice for doing stuff like that? At the moment I'm pretty sure that I should use str_replace();

UPD. I think preg_replace() would be suitable for my case. But then there is another problem: what should regexp look like in order to make my issue solved?

P.S. Just in a case I'm using SilverStripe framework (v3.1.12)

  • 写回答

5条回答 默认 最新

  • dseslyh6662605 2015-10-13 22:33
    关注
    $url = '/foo/bar/url/';
    
    if (false !== $last = strrpos($url, '/')) {
        if (false !== $penultimate = strrpos($url, '/', $last - strlen($url) - 1)) {
            $url = substr_replace($url, '/#', $penultimate, 1);
        }
    }
    
    echo $url;
    

    This will output

    /foo/bar/#url/
    

    If you want to strip the last /:

    echo rtrim($url, '/'); // print /foo/bar/#url
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路