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

时间:2019-04-06 08:55:37

标签: php html html5

下面的函数将替换&?字符,但是对于?,我希望仅在子目录{ {1}}

example.com/forum/

示例:

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

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

以下是构成论坛URL的代码:

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

1 个答案:

答案 0 :(得分:0)

您需要匹配URL字符串,以使用preg_match()检查URL中是否存在forum子目录。以后,您可以使用str_replace()从网址中删除?

<?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');

演示: https://3v4l.org/FXDml

请注意:我没有使用urlencode(),因为它也会转换URL中的其他字符,这在您的情况下也是不希望的。