Php 仅当不存在目录时,才删除URL中的最后一个斜杠
我正在尝试从URL中删除最后一个Php 仅当不存在目录时,才删除URL中的最后一个斜杠,php,regex,preg-replace,Php,Regex,Preg Replace,我正在尝试从URL中删除最后一个/,但只有在没有目录的情况下。是否有办法检查是否(仅3个斜杠和非https)删除斜杠?还是有更好的方法来完成我想做的事情 到目前为止我所拥有的 $url=preg_replace(数组('{http://}','{/$}'),''.$project->url); 当前输出: http://www.example.org/ =>www.example.org https://www.example.org/ => https://
/
,但只有在没有目录的情况下。是否有办法检查是否(仅3个斜杠和非https)删除斜杠?还是有更好的方法来完成我想做的事情
到目前为止我所拥有的
$url=preg_replace(数组('{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/
这可能不是最好的方法,但可以完成以下任务:
$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
您可以尝试以下方法:
$url = preg_replace('~^(?:(https://)|http://)?+([^/]++)(?:(/[^\s"']++)|/)?+~', '$1$2$3', $url);
或者更简单(如果$url
仅包含url)
请注意,对于这些模式:
www.example.org/
givewww.example.org
及
http://www.example.org
givewww.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
在离开或删除斜杠之前,您必须先检查是否有目录。谢谢。我用了第二个。你有没有可能再多解释一点,让我了解它在做什么,看看那里的操作顺序?谢谢
~ # 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