An Alternative to array_shift and explode? - Please Help

Discussion in 'PHP' started by 5starpix, Dec 30, 2011.

  1. #1
    Hey,

    array_shift seems to work on another server, but it does not on mine.

    The code is the following;

    $realid = array_shift(explode("-", $id));
    PHP:
    What I am trying to get done is the following;

    I have a URL, which is like [ example.com/48555-animal-name.html ]. How is it possible to ONLY get the ID which is 48555, to call an entry from the database?

    $realid = array_shift(explode("-", $id));
    $qryrec="select * from animals where id='$realid'";
    $resultrec=mysql_query($qryrec) or die($qryrec);
    $linerec=mysql_fetch_array($resultrec);
    $pcommon = ucwords($linerec[common]);
    PHP:
    Is there an another way of doing this, without using array_shift?

    Thanks,
     
    Solved! View solution.
    5starpix, Dec 30, 2011 IP
  2. #2
    
    <?php
    
    $arrays = array(
        'example.com/48555-animal-name.html',
        'example.com/48555-345-animal-na3me.html',
        '48555-animal-name.html'          
    );
    
    foreach ($arrays as $item):
        preg_match('/.*\/?([0-9]+)-/U', $item, $res);
        echo $res[1];
    endforeach;
    
    PHP:
     
    ThePHPMaster, Dec 30, 2011 IP
  3. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #3
    That really does look like you are doing it the hard way.

    I'd try something like this, takes a few more steps but is readable and debugable.
    
    $url = "example.com/48555-animal-name.html";
    $pos = 1; // how many / are expected before the id
    
    $bits =explode('/', $url);
    $idbits = explode('-',$bit[$pos]);
    $id = $idbits[0];
    
    PHP:
    edit: ThePHPMaster is onto it, preg is faster and allows subtle changes as per the example
     
    sarahk, Dec 30, 2011 IP
  4. WPC

    WPC Peon

    Messages:
    116
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Just use regex, and var_dump. Then just put the match[1] into a variable which you will use.
     
    WPC, Dec 31, 2011 IP