【问题标题】:Check if URL has content in PHP检查 URL 是否包含 PHP 中的内容
【发布时间】:2019-03-25 20:55:06
【问题描述】:

我有一个 PHP 文件。在此文件中,我需要检查我的 URL 是否具有以下结尾:

www.example.de/dashboard/2/

所以结尾可以是一个数字1 - 99+,它总是在两个斜杠之间的网址末尾。我不能在这里使用$_GET。如果是$_GET,那就简单了:

if ( isset($_GET['ending']) ) :

那么,如果没有 URL 中的参数,我该怎么做呢?感谢您的帮助!

【问题讨论】:

    标签: php html url


    【解决方案1】:
    if(preg_match('^\/dashboard\/(\d+)', $_SERVER['REQUEST_URI'])){
        foo();
    }
    
    

    在请求 uri 上使用正则表达式

    【讨论】:

    • 我有一个问题,尝试用 RegExp 解决它。现在我有两个问题:) 对于这种情况,爆炸是最好的方法。
    • 感谢您花时间帮助我!
    【解决方案2】:

    你可以使用parse_url和explode:

    $url = 'http://www.example.de/dashboard/2/';
    
    $path = parse_url($url, PHP_URL_PATH); // '/dashboard/2/'
    $parts = explode('/', $path);          // ['', 'dashboard', '2', '']
    $section = $parts[1];                  // 'dashboard'
    $ending = $parts[2];                   // '2'
    

    演示:https://3v4l.org/dv6Cn

    您也可以使用URL rewriting(这是针对基于 Apache 的网络服务器,但如果需要,您可以为 nginx 或任何其他网络服务器找到类似资源)。

    【讨论】:

    • 我会在这里拿这个,因为它很简单而且很有效:)
    【解决方案3】:

    更动态的方法是展开并使用 array_filter 删除空值,然后选择最后一项。
    如果 item * 1 与 item 相同,则我们知道它是一个数字。
    (explode 的返回是字符串,所以我们不能使用 is_int)

    $url = "http://www.example.de/dashboard/2/";
    $parts = array_filter(explode("/", $url));
    $ending = end($parts);
    if($ending*1 == $ending) echo $ending; //2
    

    【讨论】:

    • 字符串相乘会产生警告。
    • 现在尝试使用不以“数字”结尾的 URL。 PHP 以某种方式设法使用诸如“2”之类的字符串来做到这一点,因为它是一种糟糕的语言,但仍然:)
    • 感谢您花时间帮助我!
    【解决方案4】:

    首先,您需要将此 URL 定位到脚本 - 在 Web 服务器配置中。对于 nginx 和 index.php:

    try_files $uri @rewrite_location;
    location @rewrite_location {
            rewrite ^/(.*) /index.php?link=$1&$args last;
    }
    

    第二 - 你需要解析 URI。在 $end 你会找到你想要的

    $link_as_array = array_values(array_diff(explode("/", $url), array('')));
    $max = count($link_as_array) - 1;
    $end = $link_as_array[$max];
    

    【讨论】:

    • 没问题,但是您知道可以在发布之前尝试您的代码吗? 3v4l.org/uEnLp
    • 感谢您花时间帮助我!
    • 哦,该睡觉了,忘了最后一个斜线。但是这段代码一点都不好,这是模拟的,没有准备好生产。
    【解决方案5】:

    我会这样想。如果 URL 始终相同或格式相同,我将执行以下操作:

    1. 检查大概的 URL。
    2. 将 URL 拆分为多个部分。
    3. 查找是否有我要查找的部件。
    4. 提取号码。
    <?php
      $url = "http://www.example.de/dashboard/2/";
      if (strpos($url, "www.example.de/dashboard") === 7 or strpos($url, "www.example.de/dashboard") === 8) {
        $urlParts = explode("/", $url);
        if (isset($urlParts[4]) && isNumeric($urlParts[4]))
          echo "Yes! It is {$urlParts[4]}.";
      }
    ?>
    

    带有7 和8 的strpos 用于带有http:// 或https:// 的URL。

    如果已设置,上述内容将为您提供作为数字部分的输出。我希望这会成功。

    【讨论】:

    • 我认为您的 explode 缺少参数 :)
    • @Jeto 非常感谢。我已经纠正了错误。有两个。 ??‍♂️
    • 为什么不做 $urlParts[-1] ?
    • @Andreas 没有 cmets。 ?
    • 感谢您花时间帮助我!
    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 2013-02-07
    • 2018-02-05
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2012-01-05
    相关资源
    最近更新 更多