Search code examples
phpparsingsubstringpreg-replacepreg-match

How to store numeric value of the first 1-character alphabetical parameter in a URL?


I want to store in a session, a value (a number) of the first 1-character alphabetical string that shows in the URL, as long as it is not a.

Examples, if visitor arrives to:

mydomain.com/nice-url/?a=1&p=2&v=3&vt_p=5

Then the number that should be stored is 2

(something like $_SESSION['number']=2)

mydomain.com/nice-url/?a=2&v=7

Then the number that should be stored is 7

mydomain.com/nice-url/?z=3&

Then the number that should be stored is 3

mydomain.com/nice-url/?a=1&pv=2&s=30&p=5

Then the number that should be stored is 30

mydomain.com/nice-url/?a=1&v=z&m=8

Then the number that should be stored is 8

I'm already using following code for another use, so perhaps a part of this code can be utilized for this goal as well:

function unparse_url($parsed_url) {
  $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
  $pass     = ($user || $pass) ? "$pass@" : '';
  $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  $query    = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
  $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  return "$scheme$user$pass$host$port$path$query$fragment";
}

function strip_query($url, $query_to_strip) {
  $parsed = parse_url($url);
  $parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
  return unparse_url($parsed);
}

$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Solution

  • The solution using parse_url, explode and is_numeric functions:

    $url = "mydomain.com/nice-url/?a=1&pv=2&s=30&p=5";
    $query_papams = explode("&", parse_url($url, PHP_URL_QUERY));
    $number = "not found";
    
    foreach ($query_papams as $p) {
        $pair = explode("=", $p);
        if (strlen($pair[0]) == 1 && $pair[0] !== "a" && is_numeric($pair[1])) {
            $number = $pair[1];
            break;
        }
    }
    
    print_r($number);  // 30