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 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合