How to use preg_match?

Discussion in 'PHP' started by QueenZ, Mar 8, 2012.

  1. #1
    Hello, I have a problem getting user id from this string using preg match... what am I doing wrong?

    <?php            $edituser = "http://localhost/wp_users/user-edit.php?user_id=39&wp_http_referer=%2Fwordpress%2Fwp-admin%2Fusers.php%3Fs%3Dingrid%40gmail.com%26action%3D-1%26new_role%26paged%3D1%26action2%3D-1";
                
                preg_match('/user-edit.php?user_id=([a-z|0-9]+)&/', $edituser, $matches);
                echo $matches[1];
    ?>
    
    
    
    Code (markup):
    Notice: Undefined offset: 1 in /var/www/teststuff.php on line 5
     
    QueenZ, Mar 8, 2012 IP
  2. prabhunimish

    prabhunimish Member

    Messages:
    15
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    46
    #2
    try this :


    
    $url = 'http://localhost/wp_users/user-edit.php?user_id=39&wp_http_referer=%2Fwordpress%2Fwp-admin%2Fusers.php%3Fs%3Dingrid%40gmail.com%26action%3D-1%26new_role%26paged%3D1%26action2%3D-1';
    
    
    $QUERYVAR= parse_url($url, PHP_URL_QUERY);
    
    
    $GETVARS = explode('&',$QUERYVAR);
    
    
    foreach($GETVARS as $string){
         list($is,$what) = explode('=',$string);
         echo "$is -> $what<br/>";
    }
    
    Code (markup):

    if you just want the user_id value, you can take the first output only :


    
    $url = 'http://localhost/wp_users/user-edit.php?user_id=39&wp_http_referer=%2Fwordpress%2Fwp-admin%2Fusers.php%3Fs%3Dingrid%40gmail.com%26action%3D-1%26new_role%26paged%3D1%26action2%3D-1';
    
    
    $QUERYVAR = parse_url($url, PHP_URL_QUERY);
    
    
    $GETVARS = explode('&',$QUERYVAR);
    
    
    list($a,$user_id) = explode('=',$GETVARS[0]);
    
    
    echo $user_id;
    
    
    
    Code (markup):
     
    prabhunimish, Mar 8, 2012 IP
  3. bogi

    bogi Well-Known Member

    Messages:
    482
    Likes Received:
    16
    Best Answers:
    2
    Trophy Points:
    140
    #3
    Your regex pattern won't find your user_id. If it's a WordPress URL, the user_id will always be an integer, so you can use \d in your pattern.
    You also don't need to include '/user-edit.php?' because what happens if user_id is not the first variable?
    And as you use \d you can leave the '&' symbol from your pattern, so it will also find the id if it's the last element.

    See below:

    
    $edituser = 'http://localhost/wp_users/user-edit.php?user_id=39&wp_http_referer=%2Fwordpress%2Fwp-admin%2Fusers.php%3Fs%3Dingrid%40gmail.com%26action%3D-1%26new_role%26paged%3D1%26action2%3D-1';
    
    preg_match('#user_id=([\d]+)#', $edituser, $matches);
    
    echo $matches[1];
    
    PHP:
     
    bogi, Mar 10, 2012 IP