0

我正在尝试/从 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/
4

2 回答 2

1

你可以试试这个:

$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.orgwww.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
于 2013-08-07T16:57:48.083 回答
0

这可能不是最好的方法,但可以完成这项工作:

$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
于 2013-08-07T16:52:24.630 回答