how to find a string having always the same beginning in array.

Discussion in 'PHP' started by Cooker, May 6, 2009.

  1. #1
    Hi, I have got an array with many words and links.
    Iwant to have array with links starting ONLY from http://example.co,/cat/a/
    What should I do ?
    Thanks
     
    Cooker, May 6, 2009 IP
  2. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #2
    koko5, May 6, 2009 IP
  3. netwaydev

    netwaydev Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    using array_filter it would like this

    $old = array(........);

    function start_with_your_string ($var) {
    $string = 'http://example.co.uk/something/';
    return (strpos($var, $string) === 0);
    }

    $new = array_filter($old, "start_with_your_string");

    just change $string to whatever you need.
     
    netwaydev, May 6, 2009 IP
  4. austin-G

    austin-G Peon

    Messages:
    435
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Or just do this:

    $old = array(.........);
    $string = 'http://example.co.uk/something/';
    $new = array();
    
    foreach( $old as $k => $v ) {
    if( strpos( $v, $string ) !== false ) $new[] = $v;
    }
    PHP:
     
    austin-G, May 6, 2009 IP
  5. Aaron Sustar

    Aaron Sustar Peon

    Messages:
    38
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    This code has a small bug, it just checks if the string *contains* the specified substring and not if it begins with it. You might simply add a condition like this:

    if( strpos( $v, $string ) !== false && strpos( $v, $string ) < 1 ) $new[] = $v;
     
    Aaron Sustar, May 7, 2009 IP
  6. fourfingers

    fourfingers Peon

    Messages:
    37
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #6
    foreach($array as $item) {
    if (preg_match("/example.com\/ca\/a\//i",$item)) {
    array_push($final_array,$item) ;
    }
    }

    print_r($final_array) ;
     
    fourfingers, May 13, 2009 IP
  7. Gordaen

    Gordaen Peon

    Messages:
    277
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #7
    You'd want to foreach through it and use preg_match("/$http:\/\/example\.com/i, $value), replacing example\.com with whatever the full check you want to do is.
     
    Gordaen, May 13, 2009 IP