我正在尝试从网址中删除最后一个/
,但前提是没有目录。有没有办法检查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/
答案 0 :(得分:1)
你可以试试这个:
$url = preg_replace('~^(?:(https://)|http://)?+([^/]++)(?:(/[^\s"']++)|/)?+~', '$1$2$3', $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
答案 1 :(得分: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