删除URL中的最后一个斜杠,仅当不存在目录时


Remove last slash in URL, only if no directory is present

我正在尝试从URL中删除最后一个/,但前提是不存在目录。有办法检查if(3 slashes only && not https) remove slash吗?或者有更好的方法来完成我想要做的事情吗?

到目前为止我所拥有的

$url = preg_replace(array('{http://}', '{/$}'), '', $project->url);

电流输出:

http://www.example.org/          => www.example.org
https://www.example.org/         => https://www.example.org
http://www.example.org/dir/      => www.example.org/dir
https://www.example.org/dir/     => https://www.example.org/dir
http://www.example.org/dir/dir/  => www.example.org/dir/dir
https://www.example.org/dir/dir/ => https://www.example.org/dir/dir

我想要得到什么

http://www.example.org/          => www.example.org
https://www.example.org/         => https://www.example.org
http://www.example.org/dir/      => www.example.org/dir/
https://www.example.org/dir/     => https://www.example.org/dir/
http://www.example.org/dir/dir/  => www.example.org/dir/dir/
https://www.example.org/dir/dir/ => https://www.example.org/dir/dir/

你可以试试这个:

$url = preg_replace('~^(?:(https://)|http://)?+([^/]++)(?:(/[^'s"']++)|/)?+~', '$1$2$3', $url);

或者更简单(如果$url仅包含url)

$url = preg_replace('~^(?:(https://)|http://)?+([^/]++)(?:(/.++)|/)?+~', '$1$2$3', $url);

注意,使用这些模式:

www.example.org/给出www.example.org

http://www.example.org给出www.example.org

第二图案详细信息

~                         # pattern delimiter
^                         # anchor for the begining of the string
(?:(https://)|http://)?+  # optional "http(s)://" , but only "https://" 
                          # is captured in group $1 (not "http://") 
([^/]++)                  # capturing group $2: all characters except "/"
(?:(/.++)|/)?+            # a slash followed by characters (capturing group $3)
                          # or only a slash (not captured),
                          # all this part is optional "?+"
~                         # pattern delimiter

这可能不是最好的方法,但可以完成任务:

$num_slash = substr_count($url, '/');
if ($num_slash > 3)
{
    // i have directory
    if (strpos($url, ':') == 4)
        $url = substr($url, 7);
    // this will take care of 
    // http://www.example.org/dir/dir/ => www.example.org/dir/dir/
}
else
{
    $url = preg_replace(array('{http://}', '{/$}'), '', $project->url);
    // this will take care of as you already mentioned
    // http://www.example.org/  => www.example.org
    // https://www.example.org/ => https://www.example.org
}
// so whenever you have https, nothing will happen to your url