【问题标题】:How to get string after second slash in url - using php?如何在 url 中的第二个斜杠后获取字符串 - 使用 php?
【发布时间】:2014-10-22 00:44:35
【问题描述】:

如何在 url 中的第二个斜杠后获取字符串? URL 每次都不同(更多的斜杠),但每次我都需要第二个斜杠之后的整个文本。怎么做?

我正在使用此代码:

<?php
    $str = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $last = substr($str, strrpos($str, '/') - 1);
    echo $last;
?>

...但它可以在线使用斜线后的一些字符。

非常感谢您的帮助。

【问题讨论】:

  • 原始$str 的输出是什么?
  • 你指的是什么斜线?协议一或子文件夹/重写?

标签: php string url character slash


【解决方案1】:

使用

    <?php
        $str = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $last = explode("/",$str,3);// so at second index rest of the string will come.
echo $last[2];

看这里http://www.w3schools.com/php/func_string_explode.asp

【讨论】:

    【解决方案2】:
    $last = explode("/", $str, 3);
    echo $last[2];
    

    【讨论】:

    • 谢谢,就是这样-顺便说一句。安全吗?
    • 当然,但如果你愿意,你可以像 "if(isset($last[2])){ //do sth }" 一样检查它
    【解决方案3】:
    <?php
        $str = "google.com/whatever/hello";
    
        $last = GetStringAfterSecondSlashInURL($str);
    
        echo $last;
    
        function GetStringAfterSecondSlashInURL($the_url)
        {
            $parts = explode("/",$the_url,3);
    
            if(isset($parts[2]))
                return $parts[2];
        }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      相关资源
      最近更新 更多