Friday, 19 September 2014

PHP: preg_match get the id from url

<?php
//firstway
$url = 'site.com/shop/product/view?id=1&name=name';
$query_string = parse_url($url, PHP_URL_QUERY);
parse_str($query_string, $data);
echo $data['id']; // 1

//second way
$url = "site.com/shop/product/view?id=1231&name=name";
if (preg_match('/id=[0-9]*/', $url, $matches))
    $id = $matches[0];

$req_id = explode('=', $id);
echo $req_id[1];
?>

0 comments:

Post a Comment