Check last part of url with php

I am working with Zend Framework. I want to check the last part of the link. my link http://localhost/sports/soccer/page_id/776543233242


my last part of url should be 12 or 11 digits and I want the first part to start at 8 if 11 digits and start at 7 if 12 digits.

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";
     }
}

      

+3


source to share


5 answers


This should work for you:

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

?>

      



Output:

yes

      

+4


source


Use a function basename()

in php to get your last part of the url and then count the string. Check the meaning of a word with strlen

. Use below code

    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";
    }
    }

      



Hope this helps you

+1


source


See parse_url . Then you can get the path and split it into /

.

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'));
}

      

0


source


If you want to get the form of your url number, I suggest you use a regex. in this case:

$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);

      

This code outputs $out

. It will look like this:

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

      

Hope this helps you.

0


source


Obviously, the required url part matches the parameter page_id

.

With Zend Framework, you can do something like this to get the value of this parameter:

$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";

      

0


source







All Articles