简体   繁体   English

如何仅使用正则表达式从URL中提取参数值

[英]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. 使用正则表达式从该URL中提取u2参数的值。 http://www.example.com?u1=US&u2=HA853&u3=HPA 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 输出:-u2 = HA853

How can i retrieve only HA853? 我如何只能检索HA853?

The 0 group is everything that the regex matched so either use \\K to ignore the previous matches of the regex, 0组是正则表达式匹配的所有内容,因此可以使用\\K忽略正则表达式的先前匹配项,

$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. 尽管您不清楚为什么需要这样做,但http://php.net/manual/zh-CN/function.parse-str.php似乎更简单。

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

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

Other way is to use parse_url, http://php.net/manual/en/function.parse-url.php 其他方法是使用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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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