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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度