如何在url中使用第二个斜杠后获取字符串 - 使用php?

时间:2014-08-28 08:15:13

标签: php string url character slash

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

我正在使用此代码:

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

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

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

$last = explode("/", $str, 3);
echo $last[2];

答案 1 :(得分:0)

<?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];
    }

?>

答案 2 :(得分:0)

使用

    <?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