how to extract a variable part of link ?

Discussion in 'PHP' started by ramysarwat, Oct 29, 2009.

  1. #1
    how can i extract "value=" and its value which is 123456

    from this link
    http://www.example.com/test?a=dsfgksdjfgdf&value=123456

    or this link
    http://www.example.com/test?a=dsfgksdjfgdf&value=123456&b=jhdfiudsf
     
    ramysarwat, Oct 29, 2009 IP
  2. CodedCaffeine

    CodedCaffeine Peon

    Messages:
    130
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This should solve your problem:

    Here is the function I'm using:
    http://php.net/manual/en/function.parse-url.php

    So if we apply this to your source provided:

    <?php
    /*
    URL PARSE EXAMPLE
    Author: Joel Larson (Coded Caffeine)
    Author URI: http://thejoellarson.com/
    
    Enjoy!
    */
    
    #Here is the second url
    $url = 'http://www.example.com/test?a=dsfgksdjfgdf&value=123456&b=jhdfiudsf';
    
    #Extract the query segments from the url
    $uri_query = parse_url($url, PHP_URL_QUERY);
    
    #Prints out the result:
    print_r($uri_query); // a=dsfgksdjfgdf&value=123456&b=jhdfiudsf
    
    #Parse the query
    parse_str($uri_query, $segment);
    
    #Prints out the result:
    print_r($segment); //Array ( [a] => dsfgksdjfgdf [value] => 123456 [b] => jhdfiudsf )
    
    #Now, you can access these variables via the array 'segments'. It displays:
    /*
    a: dsfgksdjfgdf
    value: 123456
    b: jhdfiudsf
    */
    echo '<br /> a: ', $segment['a'], '<br /> value: ', $segment['value'], '<br /> b: ',$segment['b'];
    PHP:
    I also have this:
    function parse_uri_vars($url)
    {
    	$uri_query = parse_url($url, PHP_URL_QUERY);
    	parse_str($uri_query, $segment);
    	return $segment;
    }
    
    $url = "http://www.example.com/test?a=dsfgksdjfgdf&value=123456&b=jhdfiudsf";
    $parts = parse_uri_vars($url);
    echo $parts['value']; //Echos 123456
    
    PHP:
     
    Last edited: Oct 29, 2009
    CodedCaffeine, Oct 29, 2009 IP
    organicCyborg likes this.
  3. szalinski

    szalinski Peon

    Messages:
    341
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    $value = $_GET['value'];
    PHP:
     
    szalinski, Oct 29, 2009 IP
  4. CodedCaffeine

    CodedCaffeine Peon

    Messages:
    130
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Whoops! I was over-thinking it.. haha.
     
    CodedCaffeine, Oct 29, 2009 IP
  5. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Nope, depends really if the URL is in a variable or he's actually on the page. I thought of it from your point of view also.
     
    wd_2k6, Oct 29, 2009 IP