下面的函数将替换和
&
和?
字符,但是对于?
,我希望仅在子目录{ {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
答案 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', '&'],$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');
请注意:我没有使用urlencode()
,因为它也会转换URL中的其他字符,这在您的情况下也是不希望的。