使用preg_replace将绝对url转换为相对url


Convert absolute to relative url with preg_replace

(我搜索了一下,发现了很多关于将相对url转换为绝对url的问题,但没有关于绝对url转换为相对url的问题)

我想从一个表单字段输入,并以一个相对url结束。理想情况下,这将能够处理以下任何输入并以/page-slug结束。

  • http://example.com/page-slug
  • http://www.example.com/page-slug
  • https://example.com/page-slug
  • https://www.example.com/page-slug
  • example.com/page-slug
  • /page-slug
  • 也许还有更多我没有想到的…?

编辑:我也希望这工作的东西,其中的相对url是例如/page/post(即有多个斜杠)。

如果您总是使用url,请查看parse_url。具体来说:

parse_url($url, PHP_URL_PATH)

仅供参考,我对所有输入进行了测试,除了:example.com/page-slug

试试这个regexp

#^              The start of the string
(
   ://          Match either ://
   |            Or
   [^/]         Not a /
)*              Any number of times
#

并替换为空字符串

$pattern = '#^(://|[^/])+#';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);

我认为你想在主机名之后的URL部分,你可以使用parse_url:

$path = parse_url($url, PHP_URL_PATH);

注意,这将获得主机名后URL的整个,因此http://example.com/page/slug将给出/page/slug

如果你了解你的应用程序,我会用一种简单的方式来做。我将使用正则表达式来搜索

[a-z].([(com|org|net)])