Regex to get numeric URL parameter value?

In a URL like below, I would like to get the value of ProdId. The format of the URL will always be consistent, as will the name of the parameter, but the length of the value may change. It will always be numeric.

http://www.example.com/page.php?ProdId=2683322&xpage=2

Using PHP, what's the fastest way to get it (I will handle 10,000, so speed is the problem)?

+3
source share
5 answers

PHP has built-in functions for this. Use parse_url()and parse_str()together.

Assembled with php.net:

$url = 'http://www.example.com/page.php?ProdId=2683322&xpage=2';

// Parse the url into an array
$url_parts = parse_url($url);

// Parse the query portion of the url into an assoc. array
parse_str($url_parts['query'], $path_parts);

echo $path_parts['ProdId']; // 2683322
echo $path_parts['xpage']; // 2
+13
source

Try this regex:

^http://www\.example\.com/page\.php\?ProdId=(\d+)
+6
source

$_GET['ProdId']?

+2

:

/https?:\/{2}(?:w{3}\.)?[-.\w][^\.]+\.{2,}\/ProdId=\d+\&xpage=\d+/
+2
/^[^#?]*\?(?:[^#]*&)?ProdId=(\d+)(?:[#&]|$)/

:

  • Match anything other than ?or #(this will lead us to the beginning of the query string or hash part, whichever comes first)
  • Match ?(if there was only a hash part, this will result in disqualification of compliance)
  • It is not necessary to match something (but not # if there is a hash part), and then &
  • Match a pair of your key values ​​by placing the value in the capture subpattern
  • Match either the next param &, or #, or the end of the line.
0
source

Source: https://habr.com/ru/post/1747784/


All Articles