用php查看URL的最后一部分

时间:2015-01-12 12:02:15

标签: php zend-framework

我正在使用Zend Framework。我想查看链接的最后部分。我的链接是http://localhost/sports/soccer/page_id/776543233242 我的URL的最后一部分必须有12或11位数字,我希望该部分的第一部分以8开头,如果是11位数,则以7开头,如果是12位数。

public function detailAction ()
{

    $uri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
     if (substr(substr($uri, -12),1)=='7'){
        echo "successfull";
     }
     else if (substr(substr ($uri , -11),8)=='0'){
        echo "succ";
     }
     else {
        echo "failed";
     }
}

5 个答案:

答案 0 :(得分:4)

这应该适合你:

<?php

       $url = "http://localhost/sports/soccer/page_id/776543233242";
       $part = basename($url);

       if(strlen($part) == 11 && $part[0] == 8 || strlen($part) == 12 && $part[0] == 7)
            echo "yes";
        else
            echo "no";

?>

输出:

yes

答案 1 :(得分:1)

在php中使用basename()函数获取url的最后一部分,然后计算字符串。使用strlen检查单词的否。使用以下代码

    public function detailAction ()
{

    $url = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
           $url = "http://localhost/sports/soccer/page_id/776543233242";
           $basename = basename($url);

           if(strlen($basename) == 11 && $basename[0] == 8 || strlen($basename) == 12 && $basename[0] == 7){
                echo "succ";
    }
            else{
                echo "failed";
    }
    }

希望这有助于你

答案 2 :(得分:0)

parse_url。然后,您可以获取路径并将其拆分为/

function isValidUrl($url)
{
    $elements = parse_url($url);

    if ($elements === false) {
        return false;
    }

    $lastItem = end(explode("/", $elements['path']);
    return ((strlen($lastItem) == 12 && $lastItem[0] == '7') || (strlen($lastItem) == 11 && $lastItem[0] == '8'));
}

答案 3 :(得分:0)

如果您只想从您的网址获取该号码,我建议您使用正则表达式。在这种情况下:

$url="http://localhost/sports/soccer/page_id/776543233242";
$regex = "/[0-9]+/";
preg_match_all($regex, $url, $out); //$out will be an array storing the mathcing strings, preg_match_all creates this variable to us
var_dump($out);

此代码输出$out。它看起来像这样:

array(1) {
[0]=>
    array(1) {
    [0]=>
        string(12) "776543233242"
    }
}

我希望它会对你有所帮助。

答案 4 :(得分:0)

显然,所需网址的部分对应于page_id参数。

使用Zend Framework,您可以执行以下操作来获取此参数的值:

$page_id = $this->getRequest()->getParam('page_id');

if(strlen($page_id) == 11 && $page_id[0] == 8 
|| strlen($page_id) == 12 && $page_id[0] == 7)
    echo "yes";
else
    echo "no";