仅当没有目录时才删除URL中的最后一个斜杠

I am trying to remove the last / from a URL, but only if there is no directory present. Is there a way to check if(3 slashes only && not https) remove slash? Or is there a better way to accomplish what I am trying to do?

What I have so far

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

Current outputs:

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

What I want to get

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/

You can try this:

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

or more simple (if $url contains only an url)

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

Note that with these patterns:

www.example.org/ give www.example.org

and

http://www.example.org give www.example.org

second pattern details

~                         # 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

This might not be the best way, but will do the job:

$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