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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog