PHP:如何将尾部斜杠添加到绝对 URL [英] PHP: how to add trailing slash to absolute URL

查看:33
本文介绍了PHP:如何将尾部斜杠添加到绝对 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绝对 URL 列表.我需要确保它们都有斜杠(如适用).所以:

I have a list of absolute URLs. I need to make sure that they all have trailing slashes, as applicable. So:

  • http://www.domain.com/ <-- does not need a trailing slash
  • http://www.domain.com <-- needs a trailing slash
  • http://www.domain.com/index.php <-- does not need a trailing slash
  • http://www.domain.com/?message=hello <-- does not need a trailing slash

我猜我需要使用正则表达式,但匹配 URL 很痛苦.希望有更简单的解决方案.想法?

I'm guessing I need to use regex, but matching URLs are a pain. Was hoping for an easier solution. Ideas?

推荐答案

您可以使用 parse_url() 来做到这一点.例如:

Rather than doing this using regex, you could use parse_url() to do this. For example:

$url = parse_url("http://www.example.com/ab/abc.html?a=b#xyz");
if(!isset($url['path'])) $url['path'] = '/';
$surl = $url['scheme']."://".$url['host'].$url['path'].'?'.$url['query'].'#'.$url['fragment'];
echo $surl;

这篇关于PHP:如何将尾部斜杠添加到绝对 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆