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 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿