douxian5076 2019-04-06 08:55
浏览 25
已采纳

通过str_replace仅在特定子目录中删除“?”

The function below is replacing and & and ? characters but for ? i want the replace works only when in subdirectory example.com/forum/

public static function clean($sUrl)
    {
        return str_replace([' ', '&', '?'], ['%20', '&', ''], $sUrl);
    }

example:

https://example.com/forum/post/work/22/what-are-requirements-to-get-a-work-permit?/24

to

https://example.com/forum/post/work/22/what-are-requirements-to-get-a-work-permit/24

Here's the code that is making the forum URL:

<a href="{{ $design->url('forum', 'forum', 'post', "$topic->name,$topic->forumId,$topic->title,$topic->topicId") }}">
  • 写回答

1条回答 默认 最新

  • dsaaqdz6223 2019-04-06 13:44
    关注

    You need to match the URL string to check if forum subdirectory is present in the URL using preg_match(). Later, you can use str_replace() to remove ? from your URL.

    <?php 
    
    function removeQuestionMarks($URL){
        if(preg_match('/^http(s)?:\/\/example\.com\/forum\/.*$/',$URL) === 1){
            $URL = trim($URL);
            $URL = str_replace("?","",$URL);
        }
    
        return str_replace([' ', '&'],['%20', '&amp;'],$URL);
    }
    
    echo removeQuestionMarks('https://example.com/forum/post/work/22/what-are-requirements-to-get-a-work-permit?/24'),PHP_EOL;
    
    echo removeQuestionMarks('https://example.com/forum/ why? is it difficult?/877');
    

    Demo: https://3v4l.org/FXDml

    Note that I haven't used urlencode() as it would convert other characters in the URL too which is not desired in your case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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