简体   繁体   中英

How to extract only parameter value from URL using ONLY Regular Expressions

Extract the value of the u2 parameter from this URL using a regular expression. http://www.example.com?u1=US&u2=HA853&u3=HPA

<?php
$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet 
preg_match($pattern,$subject,$match);
print_r($match[0]);
?>

Output:- u2=HA853

How can i retrieve only HA853?

The 0 group is everything that the regex matched so either use \\K to ignore the previous matches of the regex,

$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=\K[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet 
preg_match($pattern,$subject,$match);
print_r($match[0]);

or use a second capture group:

...
$pattern='/u2=([0-9A-Za-z]*)/'; //R.E that url value is only digit/Alphabet 
...
print_r($match[1]);

Why you'd need to do that though is unclear to me, http://php.net/manual/en/function.parse-str.php , seems like a simpler approach.

$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA";
parse_str($subject, $output);
echo $output['u2'];

Demo: https://3v4l.org/gR4cb

Other way is to use parse_url, http://php.net/manual/en/function.parse-url.php

  $subject="http://www.example.com?u1=US&u2=HA853&u3=HPA";
  $query_string  = parse_url($subject, PHP_URL_QUERY); // get query string
  $parameters  = explode('&', $query_string); //Explode with &
  $array  = array();  // define an empty array
  foreach($parameters  as $val)
   {
    $param= explode('=', $val);
    $array[$param[0]] = $param[1];
   }
  echo $array['u2']; // outputs HA853

print_r($array);

Array
(
    [u1] => US
    [u2] => HA853
    [u3] => HPA
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM