【问题标题】:getting part of current page url in php在php中获取当前页面url的一部分
【发布时间】:2017-04-05 05:30:17
【问题描述】:

我有一个类似这样的网址:

http://example.com/a/b/c.php

如果我执行$_SERVER['HTTP_HOST'],我会得到example.com

如果我执行$_SERVER['REQUEST_URI'],我会得到a/b/c.php

但我希望输出为 example.com/a/ 我假设我将不得不使用一些正则表达式,但不确定如何。

欢迎提出任何建议。谢谢你:)

【问题讨论】:

  • 只需将$_SERVER['HTTP_HOST']$_SERVER['REQUEST_URI'] 组合起来即可获得网址
  • 这不是网站的 10% 之类的重复吗?哈哈
  • @mayersdesign 是的,你可能是对的,想知道为什么我在发帖之前没有先做到这一点
  • @Anusha 如果以下任何答案对您有所帮助,请考虑将其标记为答案

标签: php regex url


【解决方案1】:

我会使用explode:

<?php
$url = $_SERVER['HTTP_HOST'] . '/' . explode('/',$_SERVER['REQUEST_URI'])[1];
echo $url;
?>

【讨论】:

  • @SagarV 你看到 OP 刚刚发布的内容了吗? “这似乎可行 :) 谢谢!”
【解决方案2】:

或者以正则表达式的方式,你可以这样做:

^http(?:s)?:\/\/\K([^\/]+\/[^\/]+\/).*$

演示

示例来源 (Run Here)

$re = '/^http(?:s)?:\/\/\K([^\/]+\/[^\/]+\/).*$/m';
$str = 'http://example.com/a/b/c.php';
preg_match($re, $str, $matches);
echo $matches[1];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2014-10-14
    • 2010-11-26
    • 1970-01-01
    • 2023-03-23
    • 2011-06-17
    相关资源
    最近更新 更多